Python中TypeError: '_io.TextIOWrapper' object is not subscriptable问题解决/readlines()/with...as...

readlines()的作用

file_name = '/Users/.../test.txt'
with open(file_name,'r', encoding='utf-8') as fin:
    a = fin[1]  #取fin的第二行数据
    
Traceback (most recent call last):

  File "<ipython-input-21-3399c2345050>", line 4, in <module>
    a = fin[1]

TypeError: '_io.TextIOWrapper' object is not subscriptable

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

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

.readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型。更多关于.read()的讲解看这里

with…as…的作用

with语句能自动处理上下文环境产生的异常并且关闭文件句柄,例子如下:

file_name = '/Users/hyacinth/Desktop/irgan-master/ltr-gan/ltr-gan-pointwise/MQ2008-semi/test.txt'

with open(file_name,'r', encoding='utf-8') as fin:
    a = fin.readlines()[1]
    
b=fin.readlines()[2]

Traceback (most recent call last):

  File "<ipython-input-40-8fa20f2fe66b>", line 6, in <module>
    b=fin.readlines()[2]

ValueError: I/O operation on closed file.

fin文件已经被关闭,若不在with的嵌套中时,I/O作用在了一个已关闭的文件上,会报错ValueError: I/O operation on closed file。更多:Python中with用法及原理

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值