[英]writing data into file with binary packed format in 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)
我想用小端和大端两种方式写。
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
,而不是一个(如文档中所述)
我没有测试过,但是以下功能可以解决您的问题。 目前,它会完全读取文件内容,创建一个缓冲区,然后写出更新后的内容。 您也可以直接使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.