简体   繁体   English

为什么我不能在Python中读取超过16个字节的JPEG文件?

[英]Why can I not read more than 16 bytes of a JPEG file in Python?

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. 它读取16个字节并在控制台中显示字符串,但看起来我不能显示超过32个字节。 Why? 为什么?

When it tries to read 32 or more bytes, the output will be the same as when it read 16 bytes. 当它尝试读取32个或更多字节时,输出将与读取16个字节时的输出相同。 Why can I not read more than 16 bytes of the jpeg image? 为什么我不能读取超过16个字节的jpeg图像?

Two issues here: 这里有两个问题:

  1. Set read mode to binary. 将读取模式设置为二进制。 This way file.read function won't try to convert '\\r\\n' sequences. 这样file.read函数不会尝试转换'\\ r \\ n'序列。

  2. You're trying to print NULL-terminated string to the console. 您正在尝试将以NULL结尾的字符串打印到控制台。 print function finds first zero character in your string and terminates. print函数在字符串中查找第一个零字符并终止。 Use binascii.hexlify to convert it to the hex: 使用binascii.hexlify将其转换为十六进制:


f = open("test.jpg", "rb")
ima = f.read(16)

print "%s" % (binascii.hexlify(ima))

You probably need to set the open mode to binary: 您可能需要将打开模式设置为二进制:

f = open("test.jpg", "rb") # 'rb' here means "read mode, binary"

See this similar question for a more thorough description. 有关更详细的说明,请参阅此类似问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我们如何在python中读取16个未签名的整数(16 uint)jpeg文件 - How we can read 16 un signed integer(16 uint) jpeg files in python python从二进制文件读取16个字节的长双 - python read 16 bytes long double from binary file 如何使用Python读取每个单元格超过16个字符的Excel? - How to read an excel with more than 16 characters per cells with Python ? 如何从 python 中的文件中读取给定数量的字节? - How can I read a given amount of bytes from a file in python? 为什么在Python函数中可以使用超过2 ^ 16个常量? - Why is it possible to use more than 2 ^ 16 constants in a Python function? 如何构造一个16字节长的Python字符串? - How can I construct a Python string that is 16 bytes long? 如何读取文件的最后一个字节? - How can I read the last bytes of a file? 为什么我的 Python 读取的位比我设置的多? - Why does my Python read more bits than I have set? 为什么我必须先从BytesIO转换字节,然后再转换回BytesIO,以便可以将其读取为PDF文件响应? - Why I have to convert bytes from BytesIO then convert back to BytesIO so it can be read as PDF file response? 为什么sys.stdin.read(4).encode('utf-8')返回的字节数超过4个? - why is sys.stdin.read(4).encode('utf-8') returning more than 4 bytes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM