您正在試圖存儲32個字節長。爲什麼不把它們存儲爲二進制數字?這樣你只需要存儲每個數字32個字節而不是41個或其他。您可以添加各種準壓縮方案,以利用諸如大多數數字少於32個字節的情況。
如果您的號碼是一個字符串,將其轉換爲int
第一。 Python3 int
s爲基本無限的精度,這樣你就不會丟失任何信息:
>>> num = '113AB87C877AAE3790'
>>> num = int(num, 16)
>>> num
317825918024297625488
現在你可以將結果轉換爲字節數組,並將其寫入一個文件打開二進制寫作:
with open('output.bin', 'wb') as file:
file.write(num.to_bytes(32, byteorder='big'))
int
方法to_bytes
將您的號碼轉換爲可放置在文件中的一串字節。您需要指定字符串長度和順序。 'big'
可以更容易地讀取文件的十六進制轉儲。
讀取文件回來了,它使用int.from_bytes
以類似的方式進行解碼:
with open('output.bin', 'rb') as file:
bytes = file.read(32)
num = int.from_bytes(bytes, byteorder='big')
記住,總是包含在文件模式b
,或者如果您嘗試讀取你可能會遇到意想不到的問題或寫入代碼爲\n
的數據。
無論是讀取和寫入操作可以循環作爲理所當然的事。
無關記:'\ n'只需要一個字節。在Windows上,行尾是'\ r \ n',它需要兩個字節。 – wecsam
你有沒有考慮將文件存儲爲二進制文件? –
相關備註:您可能想了解MIDI格式如何存儲數字。基本上,有一個字節數組,但只使用每個字節的低七位。這些七位段被連接在一起形成大整數。除了最後一個字節以外的所有字節的最高位爲0(或者也許是另一種方式......我不記得了)。全部0的所有連續字節從左側省略。 – wecsam