首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python3中出现“”_io.TextIOWrapper“”对象不可订阅错误“”

python3中出现“”_io.TextIOWrapper“”对象不可订阅错误“”
EN

Stack Overflow用户
提问于 2020-04-16 10:52:10
回答 1查看 59关注 0票数 0

我正在做一个小程序,为了把我的一天都吃光!我正在读取一个文件,并将每行存储在一个变量中,如下所示:

代码语言:javascript
复制
cline = f[num_lines]

我不知道为什么这一行会出现这个错误,下面是我的完整代码:

代码语言:javascript
复制
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))

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-16 15:03:12

这条线

代码语言:javascript
复制
cline = f[num_lines] 

不起作用,因为f是一个TextIOWrapper (或文件)对象,并且它没有提供允许[index]操作的__getitem__方法。此外,未定义num_lines。当前行的内容已经保存在变量line中,因此不需要定义cline

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

代码语言:javascript
复制
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测试每行的开头,从而减少代码量。

代码语言:javascript
复制
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))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61241899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档