为什么我不能在 Python 中读取超过 16 个字节的 JPEG 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4664343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can I not read more than 16 bytes of a JPEG file in Python?
提问by andrepcg
I am trying to read a JPG image in Python.
我正在尝试用 Python 读取 JPG 图像。
So far i have:
到目前为止,我有:
f = open("test.jpg")
ima = f.read(16)
print "'%s'"% (ima)
It reads 16 bytes and displays the string in console, but it looks like I cannot display more than 32 bytes. Why?
它读取 16 个字节并在控制台中显示字符串,但看起来我不能显示超过 32 个字节。为什么?
When it tries to read 32 or more bytes, the output will be the same as when it read 16 bytes. Why can I not read more than 16 bytes of the jpeg image?
当它尝试读取 32 个或更多字节时,输出将与读取 16 个字节时相同。为什么我不能读取超过 16 个字节的 jpeg 图像?
采纳答案by yurymik
Two issues here:
这里有两个问题:
Set read mode to binary. This way
file.readfunction won't try to convert '\r\n' sequences.You're trying to print NULL-terminated string to the console.
printfunction finds first zero character in your string and terminates. Usebinascii.hexlifyto convert it to the hex:
将读取模式设置为二进制。这种方式
file.read函数不会尝试转换 '\r\n' 序列。您正在尝试将 NULL 终止的字符串打印到控制台。
print函数在您的字符串中找到第一个零字符并终止。使用binascii.hexlify将其转换为十六进制:
f = open("test.jpg", "rb")
ima = f.read(16)
print "%s" % (binascii.hexlify(ima))
回答by inkedmn
You probably need to set the open mode to binary:
您可能需要将打开模式设置为二进制:
f = open("test.jpg", "rb") # 'rb' here means "read mode, binary"
See this similar questionfor a more thorough description.
有关更详尽的描述,请参阅此类似问题。

