2014-05-19 23 views
0

我正在讀取文件的某個值,並且想要將修改後的值寫入文件。我的文件是.ktx格式[二進制打包格式]。在Python中使用二進制打包格式將數據寫入文件

我使用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) 

我想兩者兼得小端和大端寫。

+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,而不是一個(如也包括在文檔)

+0

感謝您的回覆。我已經添加了這些行:no = struct.pack(「<1」,數字)outfile.write(no)這裏number是我修改的十六進制值,我想寫入文件。現在我得到錯誤「結構。錯誤:包需要0正確的參數」與該代碼 – debonair

+0

多數民衆贊成,因爲它是一個小寫的L不是一個... –

0

我還沒有測試過,但下面的函數應該可以解決你的問題。目前它完全讀取文件內容,創建一個緩衝區,然後寫出更新的內容。您也可以使用unpack_frompack_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)