問題描述
我使用 python 3我嘗試將二進制文件寫入我使用 r+b 的文件.
I use python 3 I tried to write binary to file I use r+b.
for bit in binary:
fileout.write(bit)
其中 binary 是一個包含數字的列表.如何將其寫入二進制文件?
where binary is a list that contain numbers. How do I write this to file in binary?
最終文件必須看起來像b' x07x08x07
The end file have to look like b' x07x08x07
謝謝
推薦答案
當您以二進制模式打開文件時,您實際上是在使用 bytes
類型.因此,當您寫入文件時,您需要傳遞一個 bytes
對象,而當您從中讀取時,您會得到一個 bytes
對象.相反,當以文本模式打開文件時,您正在使用 str
對象.
When you open a file in binary mode, then you are essentially working with the bytes
type. So when you write to the file, you need to pass a bytes
object, and when you read from it, you get a bytes
object. In contrast, when opening the file in text mode, you are working with str
objects.
所以,寫二進制"其實就是寫字節串:
So, writing "binary" is really writing a bytes string:
with open(fileName, 'br+') as f:
f.write(b'x07x08x07')
如果你有實際的整數想要寫成二進制,你可以使用 bytes
函數將整數序列轉換為字節對象:
If you have actual integers you want to write as binary, you can use the bytes
function to convert a sequence of integers into a bytes object:
>>> lst = [7, 8, 7]
>>> bytes(lst)
b'x07x08x07'
結合這一點,您可以將整數序列作為字節對象寫入以二進制模式打開的文件中.
Combining this, you can write a sequence of integers as a bytes object into a file opened in binary mode.
正如 Hyperboreus 在評論中指出的那樣,bytes
只會接受實際上適合一個字節的數字序列,即 0 到 255 之間的數字.如果你想存儲任意(正)整數以它們的方式,不必費心知道它們的確切大小(這是結構所必需的),然后您可以輕松編寫一個輔助函數,將這些數字分成單獨的字節:
As Hyperboreus pointed out in the comments, bytes
will only accept a sequence of numbers that actually fit in a byte, i.e. numbers between 0 and 255. If you want to store arbitrary (positive) integers in the way they are, without having to bother about knowing their exact size (which is required for struct), then you can easily write a helper function which splits those numbers up into separate bytes:
def splitNumber (num):
lst = []
while num > 0:
lst.append(num & 0xFF)
num >>= 8
return lst[::-1]
bytes(splitNumber(12345678901234567890))
# b'xabTxa9x8cxebx1f
xd2'
因此,如果您有一個數字列表,則可以輕松地遍歷它們并將每個數字寫入文件;如果您想稍后單獨提取數字,您可能需要添加一些東西來跟蹤哪些單個字節屬于哪些數字.
So if you have a list of numbers, you can easily iterate over them and write each into the file; if you want to extract the numbers individually later you probably want to add something that keeps track of which individual bytes belong to which numbers.
with open(fileName, 'br+') as f:
for number in numbers:
f.write(bytes(splitNumber(number)))
這篇關于Python編寫二進制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!