什么替代Python 3中的xreadlines()?

在Python 2中,文件对象有一个xreadlines()方法,它返回一个迭代器,一次读取一行文件。在Python 3中,xreadlines()方法不再存在,而realines()仍然返回一个列表(不是迭代器)。 Python 3有类似于xreadlines()的东西吗? 我知道我能做到
for line in f:
代替
for line in f.xreadlines():
但我还想使用没有for循环的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.997268450092n'
>>> next(f)
'2,B,-0.081127897359,2.05114559572n'
使用
itertools.islice
从迭代中获取任意元素。
>>> f.seek(0)
0
>>> next(islice(f, 7, None))
'8,A,-0.0518101108474,12.094341554n'
    
怎么样(生成器表达式):
>>> f = open("r2h_jvs")
>>> h = (x for x in f)
>>> type(h)
<type 'generator'>`
    

要回复问题请先登录注册