首页 > 解决方案 > '_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))

提前谢谢你我不知道为什么这不起作用。

标签: python

解决方案


线

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))

推荐阅读