python - '_io.TextIOWrapper' 对象在 python3 中不是可下标的错误
问题描述
我正在做一个小程序来为我吃掉我的一天!我正在读取一个文件并将每一行存储在一个变量中,如下所示:
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))
提前谢谢你我不知道为什么这不起作用。
解决方案
线
cline = f[num_lines]
不起作用,因为f
它是一个TextIOWrapper
(或文件)对象,并且它不提供__getitem__
允许[index]
操作的方法。另外,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))
推荐阅读
- excel - 避免突出显示不打算显示的行
- html - Bootstrap4、btn 和 btn-primary 类不适用于链接(“a”标签)
- javascript - HighChart 数据表自定义导出
- user-interface - 单击后将鼠标悬停时如何突出显示按钮颜色?
- php - phpmailer没有在html中显示图像
- javascript - 使用 Bower 安装 AdminLTE
- objective-c - 如何使用objective c压缩和发送文件?
- image-processing - 如何在不破坏字符的情况下将图像分割成块 - python
- javascript - 在对象数组中查找和替换部分属性值
- python - Python:如何从列表中的一个对象中获取两个整数