TypeError: ‘_io.TextIOWrapper’ object is not subscriptable

TypeError: ‘_io.TextIOWrapper’ object is not subscriptable表示文件不能用下标进行索引。改正代码如下即可正常运行:

错误代码示范:

file_name = '/test.txt'
with open(file_name,'r', encoding='utf-8') as name:
    a = name[1]  #取name的第二行数据

 改正之后的代码:

file_name = '/test.txt'
with open(file_name,'r', encoding='utf-8') as name:
    a = name.readlines()[1]


# .readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型

你可能感兴趣的:(python,bug)