[英]python error on struct.unpack
I am new to python and I am trying to use unpack like this: 我是python的新手,正在尝试使用像这样的解压缩:
data = f.read(4)
AAA=len(data)
BBB=struct.calcsize(cformat)
print AAA
print BBB
value = struct.unpack(cformat, data)
return value[0]
This runs fine as long as AAA == BBB but sometimes, f.read only reads 3 bytes and then I get an error. 只要AAA == BBB,它就可以正常运行,但有时f.read仅读取3个字节,然后出现错误。 The actual value in the file that I am trying to read is 26. It reads all of the values from 1-221 except for 26 where it errors because f.read(size) only reads three bytes 我尝试读取的文件中的实际值为26。它会读取1-221中的所有值,但26会出错,因为f.read(size)仅读取三个字节。
Assuming the question is "How should I read a 26 without an error?" 假设问题是“我应该如何正确读取26?”
First check the arguments to the open()
that produces f
. 首先检查产生f
的open()
的参数。 Under Windows, unless you open a file in binary mode ( f = open(filename, "rb")
), Python assumes that the file is a text file. 在Windows下,除非您以二进制模式( f = open(filename, "rb")
)打开文件,否则Python会假定该文件是文本文件。 Windows treats byte value 26 (Ctrl+Z) in a text file as an end-of-file marker, a quirk that it inherited from CP/M . Windows将文本文件中的字节值26(Ctrl + Z)视为文件结束标记,这是它从CP / M继承的怪癖。
You have opened a binary file in text mode, and you are using an operating system where the distinction matters. 您已经以文本模式打开了一个二进制文件,并且所使用的操作系统对区别很重要。 Try adding b
to the mode parameter when you open the file: 尝试在打开文件时将b
添加到mode参数:
f = open("my_input_file.bin", "rb")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.