在Python 2中,文件对象具有一个XreadLines()方法,该方法返回了一个可以一次读取文件一行的迭代器。在Python 3中,XreadLines()方法不再存在,并且eneAnes()仍然返回列表(不是迭代器)。 Python 3是否具有类似于Xreadlines()类似的东西?

我知道我可以做

for line in f:

代替

for line in f.xreadlines():

但是我也想使用xReadlines()而无需循环:

print(f.xreadlines()[7]) #read lines 0 to 7 and prints line 7
有帮助吗?

解决方案

文件对象本身已经是一个值得一提的。

>>> f = open('1.txt')
>>> f
<_io.TextIOWrapper name='1.txt' encoding='UTF-8'>
>>> next(f)
'1,B,-0.0522642316338,0.997268450092\n'
>>> next(f)
'2,B,-0.081127897359,2.05114559572\n'

采用 itertools.islice 从峰值中获取任意元素。

>>> f.seek(0)
0
>>> next(islice(f, 7, None))
'8,A,-0.0518101108474,12.094341554\n'

其他提示

怎么样(发电机表达式):

>>> f = open("r2h_jvs")
>>> h = (x for x in f)
>>> type(h)
<type 'generator'>`
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top