我正在做一个小程序,为了把我的一天都吃光!我正在读取一个文件,并将每行存储在一个变量中,如下所示:
cline = f[num_lines]我不知道为什么这一行会出现这个错误,下面是我的完整代码:
import os
number_lines = 1
print('Enter the filepath to the file you want to read.')
fpath = input('Enter: ')
print('okay')
with open(fpath, 'r') as f:
for line in f:
cline = f[num_lines]
originalline = number_lines
number_lines += 1
length = len(line)
if cline[0] == 'e' and cline[1] == 'c' and cline[2] == 'h' and cline[3] == 'o' and cline[4] == '':
echoing = cline[5:length]
print(echoing)
else:
print('N# Does not recognize that command! In line: ' + str(originalline))提前谢谢你,我不知道为什么这不起作用。
发布于 2020-04-16 15:03:12
这条线
cline = f[num_lines] 不起作用,因为f是一个TextIOWrapper (或文件)对象,并且它没有提供允许[index]操作的__getitem__方法。此外,未定义num_lines。当前行的内容已经保存在变量line中,因此不需要定义cline。
这个版本的代码可以工作(我将最后的字符串测试修改为line[4] == " ",因为line[4] == ""永远不可能为真)。
number_lines = 1
print("Enter the filepath to the file you want to read.")
fpath = input("Enter: ")
print("okay")
with open(fpath, "r") as f:
for line in f:
originalline = number_lines
number_lines += 1
length = len(line)
if (
line[0] == "e"
and line[1] == "c"
and line[2] == "h"
and line[3] == "o"
and line[4] == " "
):
echoing = line[5:length]
print(echoing)
else:
print("N# Does not recognize that command! In line: " + str(originalline))如果需要,可以使用enumerate内置函数跟踪行号,使用str.startswith测试每行的开头,从而减少代码量。
print("Enter the filepath to the file you want to read.")
fpath = input("Enter: ")
print("okay")
with open(fpath, "r") as f:
for number_lines, line in enumerate(f, start=1):
length = len(line)
if line.startswith("echo "):
echoing = line[5:length]
print(echoing)
else:
print("N# Does not recognize that command! In line: " + str(number_lines))https://stackoverflow.com/questions/61241899
复制相似问题