我使用的是 Python 3,用于缓冲文件 I/O 的 peek() 方法似乎没有按照记录工作。例如,下面的代码说明了这个问题——它将 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))
有时我想在不移动文件指针的情况下查看下一个字节,但由于上面的方法不起作用,所以我在这些地方做了一些事情:
next_byte = f.read(1) # read a byte
f.seek(-1,1) # move the file pointer back one byte
这行得通,但感觉像是一个拼凑。我对 peek() 的工作原理有什么误解吗?
最佳答案
来自Python docs :
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.
强调我的。
由于文件指针在 peek
中没有移动,因此 peek
读取的内容是否超过您想要的数量并不重要。 peek 后取一个子字符串:next_byte = f.peek(1)[:1]
关于Python:为什么 peek(1) 返回 8K 字节而不是 1 字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070952/