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