Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
‘_io.TextIOWrapper’;对象不是python3中的可下标错误_Python - Fatal编程技术网

‘_io.TextIOWrapper’;对象不是python3中的可下标错误

‘_io.TextIOWrapper’;对象不是python3中的可下标错误,python,Python,我正在做一个小计划,为我消磨我的一天!我正在读取一个文件,并将每一行存储在一个变量中,如下所示: 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:

我正在做一个小计划,为我消磨我的一天!我正在读取一个文件,并将每一行存储在一个变量中,如下所示:

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
(或文件)对象,并且它不提供
\uuu getitem\uuuuu
方法,该方法允许
[index]
操作。此外,
num_行
未定义。当前行的内容已经保存在变量
line
中,因此不需要定义
cline

这个版本的代码有效(我将最后的字符串测试修改为
line[4]==”
,因为
line[4]==”
永远不可能为真)

如果您愿意,您可以通过使用内置函数来跟踪第th行编号并测试每行的开头来减少代码量

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