来自文档:
readlines(hint=-1)
Read and 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.
提示的真正含义是什么?
在某些环境中:
python3 -c 'from io import StringIO;print(StringIO(u"hello\n"*10).readlines(6));import sys;print(sys.version_info[0:3])'
['hello\n', 'hello\n']
(3, 3, 0)
python -c 'from io import StringIO;print(StringIO(u"hello\n"*10).readlines(6));import sys;print(sys.version_info[0:3])'
[u'hello\n', u'hello\n']
(2, 7, 2)
python -c 'from io import StringIO;print(StringIO(u"hello\n"*10).readlines(6));import sys;print(sys.version_info[0:3])'
[u'hello\n']
(2, 6, 6)
为什么要超过 6 个字符?
但在我的机器中,我无法取消缓冲文本 I/O。
>>> import sys
>>> sys.version
'3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 01:25:11) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> open('/etc/hosts','r',3).readlines(3)
['##\n', '# Host Database\n']
>>> open('/etc/hosts','r',0).readlines(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: can't have unbuffered text I/O
>>>
还是这种方法的错误?
2013/02/25 更新:
我检查了源代码(来自 python 2.6/2.7/ 3.x),但我无法解释:
def readlines(self, hint=None):
"""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.
"""
if hint is None or hint <= 0:
return list(self)
n = 0
lines = []
for line in self:
lines.append(line)
n += len(line)
if n >= hint:
break
return lines