我在
Windows 8上使用
Python 3.4.1.
我想读一个带缓冲接口的文件,它允许我查看前面的一定数量的字节以及读取字节. io.BufferedReader似乎是正确的选择.
不幸的是,io.BufferReader.peek似乎没用,因为它似乎只返回缓冲区中存储的所有字节,而不是请求的数字.事实上,这个函数的文档允许这样做(强调我的):
peek([size]) Return bytes from the stream without advancing the
position. At most one single read on the raw stream is done to satisfy
the call. The number of bytes returned may be less or more than
requested.
为了演示我认为无用的行为,我有以下测试文件名为Test1.txt:
first line
second line
third line
我在IDLE中创建了这样的io.BufferedReader对象:
>>> stream = io.BufferedReader(io.FileIO('Test1.txt'))
然后要求两个字节,
>>> stream.peek(2)
b'first line\r\nsecond line\r\nthird line'
嗯?这只是默认缓冲区大小中的所有文本(在我的系统上是8192字节).如果我改变了这个默认值,我可以确认peek()只是返回缓冲区的内容,
>>> stream2 = io.BufferedRead