python - while循环: 'no output' issue

标签 python while-loop output

我的任务是: “编写一个程序,读取并打印出以给定字母开头的所有行。文件路径和起始字母将作为命令行参数给出。您可以假设所有命令行参数都有效”

例如

$ cat cats.txt
calico
siamese
ginger
cute, cuddly

$ python3 filter.py cats.txt c
calico
cute, cuddly

$ python3 filter.py cats.txt g
ginger

我的代码现在看起来像:

import sys
with open("cats.txt", "r") as f:
   a = f.readlines()
   word_no = 0
   l = len(a) - 1
   while word_no <= l:
       if (a[word_no][0]) == sys.argv[1]:
           print (a[word_no])
       word_no += 1

但是,我没有通过测试用例,因为我的代码显示没有输出,即使它适用于示例文本文件? enter image description here

最佳答案

您的代码中似乎存在一些错误 - 硬编码文件路径、sys.argv 索引不正确以及使用 \n 打印行。更正后的代码:

import sys
with open(sys.argv[1], "r") as f:
   a = f.readlines()
   word_no = 0
   l = len(a) - 1
   while word_no <= l:
       if (a[word_no][0]) == sys.argv[2]:
           print (a[word_no].strip())
       word_no += 1

此外,编写此代码的更好方法是:

import sys
with open(sys.argv[1], "r") as f:
    for line in f:
        if line[0] == sys.argv[2]:
            print(line.strip())

关于python - while循环: 'no output' issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244240/

相关文章:

c - scanf函数测试

有人可以向我解释一下代码的工作原理吗?这段代码应该打印一个数字的反转

python - 清理打印命令

python - Django1.9 : 'function' object has no attribute '_meta'

While 循环中的 JavaScript PHP

Javascript 将 2 个字段与 PHP while 循环内的第三个字段中的答案相乘

python - 并行计算-将每个进程输出到文件

文件和终端上的 Python 输出

python - 使用 pymssql 的 Kerberos 委派(双跳)

Python 在数组中插入缺失的元素