简体   繁体   English

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

[英]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.

相关问题 为什么python3k的pyserial返回字节,而python2k返回字符串? - Why does pyserial for python3k return bytes while python2k returns strings? 为什么Python中的bytearray函数将一个字节变成两个字节? - Why does bytearray function in Python turn one byte into two bytes? 为什么 to_bytes(2, byteorder="big") 有时只返回一个字节? - Why does to_bytes(2, byteorder="big") return sometimes only one byte? 为什么 Python 对于 a, b == 2, 3 返回 (2, False, 3) 而不是 True? - Why does Python return (2, False, 3) instead of True for a, b == 2, 3? 为什么map在Python 3中返回地图对象而不是列表? - Why does map return a map object instead of a list in Python 3? 为什么python`any`返回bool而不是值? - Why does python `any` return a bool instead of the value? 为什么Python的iter()在映射上返回iterkeys()而不是iteritems()? - Why does Python's iter() on a mapping return iterkeys() instead of iteritems()? 为什么 python strtobool 方法返回 Int 而不是 bool? - Why does the python strtobool method return an Int instead of a bool? Python 为什么函数返回 None 而不是 False - Python Why does the fucntion return None instead of False 为什么dict(k = 4,z = 2).update(dict(l = 1))在Python中返回None? - Why does dict(k=4, z=2).update(dict(l=1)) return None in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM