我正在读取文件的某些值,并希望将修改后的值写入文件。我的文件是.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)
我想用little-endian和big-endian两种方式写作。
答案 0 :(得分: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 :(得分: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)