Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('/junk/so/foo.txt')
>>> type(f.readlines())
<class 'list'>
>>> help(f.readlines)
Help on built-in function readlines:
readlines(...)
Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
>>>
from itertools import islice
f = open('myfile.txt')
oddlines = islice(f, 0, None, 2)
firstfiveodd = islice(oddlines, 5)
for line in firstfiveodd:
print(line)
像这样:
其他人已经说过很多了,但是仅仅为了说明问题,普通的文件对象是它们自己的迭代器。所以让
readlines()
返回迭代器是愚蠢的,因为它只会返回您调用它的文件。您可以使用for
循环遍历文件,如Scott所说,还可以将它们直接传递给itertools函数:readlines方法在Python 3中不返回迭代器,而是返回一个列表
要检查,只需从交互式会话调用它-它将返回一个列表,而不是迭代器:
在这种情况下,潜入Python似乎是错误的。
当文件对象成为它们自己的迭代器时,
xreadlines
一直是deprecated since Python 2.3。获得与xreadlines
相同效率的方法不是使用you should use simply
这将为您提供所需的迭代器,并有助于解释为什么
readlines
不需要在Python 3中更改其行为-它仍然可以返回完整的列表,而line in f
习惯用法给出了迭代方法,并且已完全删除了长期不推荐的xreadlines
。相关问题 更多 >
编程相关推荐