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

本文详细解析了Python中readlines()函数的功能,它能够一次性读取整个文件的所有行并返回list类型的数据。此外,还介绍了with语句在文件操作中的应用,它能确保文件被正确关闭,避免I/O操作于已关闭文件引发的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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用法及原理

Traceback (most recent call last): File "/home/sever/PycharmProjects/pythonProject1/5m vs 6m.py", line 8, in <module> data = pd.read_csv(file_path) ^^^^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1026, in read_csv return _read(filepath_or_buffer, kwds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 626, in _read return parser.read(nrows) ^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/io/parsers/readers.py", line 1968, in read df = DataFrame( ^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/core/frame.py", line 778, in __init__ mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/core/internals/construction.py", line 443, in dict_to_mgr arrays = Series(data, index=columns, dtype=object) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/core/series.py", line 490, in __init__ index = ensure_index(index) ^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 7647, in ensure_index return Index(index_like, copy=copy, tupleize_cols=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/core/indexes/base.py", line 565, in __new__ arr = sanitize_array(data, None, dtype=dtype, copy=copy) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/core/construction.py", line 654, in sanitize_array subarr = maybe_convert_platform(data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/sever/anaconda3/envs/seaborn/lib/python3.11/site-packages/pandas/core/dtypes/cast.py", line 138, in maybe_convert_platform arr = lib.maybe_convert_objects(arr) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "lib.pyx", line 2538, in pandas._libs.lib.maybe_convert_objects TypeError: Cannot convert numpy.ndarray to numpy.ndarray
03-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值