我的任务是: “编写一个程序,读取并打印出以给定字母开头的所有行。文件路径和起始字母将作为命令行参数给出。您可以假设所有命令行参数都有效”
例如
$ 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
最佳答案
您的代码中似乎存在一些错误 - 硬编码文件路径、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/