本文介绍了什么替代Python 3中的xreadlines()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python 2中,文件对象有一个xreadlines()方法,它返回一个迭代器,一次读取一行文件。在Python 3中,xreadlines()方法不再存在,而realines()仍然返回一个列表(而不是迭代器)。 Python 3有类似于xreadlines()的东西吗?
In Python 2, file objects had an xreadlines() method which returned an iterator that would read the file one line at a time. In Python 3, the xreadlines() method no longer exists, and realines() still returns a list (not an iterator). Does Python 3 has something similar to xreadlines()?
我知道我能做到
for line in f:
而不是
for line in f.xreadlines():
但我还想使用没有for循环的xreadlines():
But I would also like to use xreadlines() without a for loop:
print(f.xreadlines()[7]) #read lines 0 to 7 and prints line 7
推荐答案
文件对象本身已经是可迭代的。
The file object itself is already an iterable.
>>> 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'
从可迭代中获取任意元素。
Use itertools.islice
to get an arbitrary element from an iterable.
>>> f.seek(0)
0
>>> next(islice(f, 7, None))
'8,A,-0.0518101108474,12.094341554\n'
这篇关于什么替代Python 3中的xreadlines()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!