用Python以二进制打包格式写入文件数据
我正在读取一个文件中的某些值,并想把修改后的值写回文件。我的文件是 .ktx 格式的,这是一种二进制打包格式。
我正在使用 struct.pack() 来处理这些数据,但似乎出现了一些问题:
bytes = file.read(4)
bytesAsInt = struct.unpack("l",bytes)
number=1+(bytesAsInt[0])
number=hex(number)
no=struct.pack("1",number)
outfile.write(no)
我想以小端和大端两种方式写入数据。
2 个回答
0
我还没测试过这个,不过下面这个函数应该能解决你的问题。现在它是先把文件内容全部读出来,创建一个缓冲区,然后再把更新后的内容写出去。你也可以直接用 unpack_from
和 pack_into
来修改文件缓冲区,但这样可能会慢一点(再次强调,我没有测试过)。我用的是 struct.Struct
类,因为你似乎想要多次解包同一个数字。
import os
import struct
from StringIO import StringIO
def modify_values(in_file, out_file, increment=1, num_code="i", endian="<"):
with open(in_file, "rb") as file_h:
content = file_h.read()
num = struct.Struct(endian + num_code)
buf = StringIO()
try:
while len(content) >= num.size:
value = num.unpack(content[:num.size])[0]
value += increment
buf.write(num.pack(value))
content = content[num.size:]
except Exception as err:
# handle
else:
buf.seek(0)
with open(out_file, "wb") as file_h:
file_h.write(buf.read())
另外一个选择是使用 array
,这样会简单很多。不过我不知道怎么在 array
中实现字节序的问题。
def modify_values(filename, increment=1, num_code="i"):
with open(filename, "rb") as file_h:
arr = array("i", file_h.read())
for i in range(len(arr)):
arr[i] += increment
with open(filename, "wb") as file_h:
arr.tofile(file_h)
0
no_little =struct.pack(">1",bytesAsInt)
no_big =struct.pack("<1",bytesAsInt) # i think this is default ...
你可以查看文档,了解你需要的格式字符,链接在这里: https://docs.python.org/3/library/struct.html
>>> struct.unpack("l","\x05\x04\x03\03")
(50529285,)
>>> struct.pack("l",50529285)
'\x05\x04\x03\x03'
>>> struct.pack("<l",50529285)
'\x05\x04\x03\x03'
>>> struct.pack(">l",50529285)
'\x03\x03\x04\x05'
另外要注意,这里是小写的 L
,不是数字1(文档里也有提到这一点)