[英]Python: why does peek(1) return 8K bytes instead of 1 byte?
I'm using Python 3, and the peek() method for buffered file I/O doesn't seem to work as documented. 我正在使用Python 3,缓冲文件I / O的peek()方法似乎没有记录。 For example, the following code illustrates the problem -- it prints 8192 as the length of the byte string returned by
f.peek(1)
: 例如,下面的代码说明了问题 - 它打印8192作为
f.peek(1)
返回的字节串的长度:
jpg_file = 'DRM_1851.JPG'
with open(jpg_file, 'rb') as f:
next_byte = f.peek(1)
print(len(next_byte))
I sometimes want to peek at the next byte without moving the file pointer, but since the above doesn't work I'm doing something this in those places instead: 我有时想在不移动文件指针的情况下查看下一个字节,但由于上述方法不起作用,我在这些地方做了一些事情:
next_byte = f.read(1) # read a byte
f.seek(-1,1) # move the file pointer back one byte
That works, but feels like a kludge. 这是有效的,但感觉像一个kludge。 Am I misunderstanding something about how peek() works?
我是否误解了peek()的工作原理?
From the Python docs : 从Python文档 :
peek([size])
PEEK([大小])
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.
返回的字节数可能少于或多于请求的数量。
Emphasis mine. 强调我的。
Since the file pointer isn't moved in peek
, it doesn't really matter if peek
reads more than the amount you want. 由于文件指针不移动
peek
,它其实并不重要,如果peek
读取比你要的量多。 Just take a substring after you peek: next_byte = f.peek(1)[:1]
偷看后只需要一个子串:
next_byte = f.peek(1)[:1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.