Man*_*áoz 73 python binary integer file
我正在尝试用Python 读取BMP文件.我知道前两个字节表示BMP公司.接下来的4个字节是文件大小.当我执行:
fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
Run Code Online (Sandbox Code Playgroud)
我明白了:
ValueError:int()的基数为10的无效文字:'F#\ x13'
我想要做的是将这四个字节作为整数读取,但似乎Python将它们作为字符读取并返回一个字符串,该字符串无法转换为整数.我该怎么做才能正确?
cod*_*ape 110
该read方法返回一个字节序列作为字符串.要从字符串字节序列转换为二进制数据,请使用内置struct模块:http://docs.python.org/library/struct.html.
import struct
print(struct.unpack('i', fin.read(4)))
Run Code Online (Sandbox Code Playgroud)
请注意,unpack始终返回一个元组,因此struct.unpack('i', fin.read(4))[0]给出您所追求的整数值.
您应该使用格式字符串'<i'(<是一个修饰符,表示little-endian字节顺序和标准大小和对齐 - 默认是使用平台的字节顺序,大小和对齐).根据BMP格式规范,字节应以Intel/little-endian字节顺序写入.
Ema*_* Ey 41
另一种不使用'struct.unpack()'的方法是使用NumPy:
import numpy as np
f = open("file.bin", "r")
a = np.fromfile(f, dtype=np.uint32)
Run Code Online (Sandbox Code Playgroud)
'dtype'表示数据类型,可以是int#,uint#,float#,complex#或用户定义的类型.见numpy.fromfile.
个人更喜欢使用NumPy来处理数组/矩阵数据,因为它比使用Python列表快得多.
Cre*_*oat 11
从Python 3.2+开始,您还可以使用from_bytesnative int方法完成此操作:
file_size = int.from_bytes(fin.read(2), byteorder='big')
Run Code Online (Sandbox Code Playgroud)
请注意,此函数要求您指定数字是以大端还是小端格式编码,因此您必须确定字节序以确保其正常工作.
除了struct你也可以使用array模块
import array
values = array.array('l') # array of long integers
values.read(fin, 1) # read 1 integer
file_size = values[0]
Run Code Online (Sandbox Code Playgroud)