문제

I'm using Python 3, and the peek() method for buffered file I/O doesn't seem to work as documented. For example, the following code illustrates the problem -- it prints 8192 as the length of the byte string returned by 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. Am I misunderstanding something about how peek() works?

도움이 되었습니까?

해결책

From the 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.

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. Just take a substring after you peek: next_byte = f.peek(1)[:1]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top