Python:为什么 peek(1) 返回 8K 字节而不是 1 字节?

标签 python file-io peek

我使用的是 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/

相关文章:

C 相当于 c++ cin.peek()

peek - 帮助 : ZX81 'BASIC' Peek function

c++ - 你如何计算 C++ 中文本文件每一行中的单词数?

python - 整数除法在 CPython 2.7 和 Spyder 中给出不同的结果

python - 以编程方式逐像素生成视频

swift - Vapor Swift 如何删除从 fileIO 收集的文件

c - 如何以优化方式加载更大的文本文件到缓冲区--c程序

c - 打开文件以从 Solaris 中用 C 编写的共享库进行写入

python - 如何识别字符串中的非字母

python - 如何将 Python 的 cmd 类的输入/输出传输到另一个 Python 进程?