問題描述
我在 Python 中有一個字符串(也可以是整數),我想將它寫入文件.它只包含 1 和 0 我希望將這種 1 和 0 的模式寫入文件.我想直接編寫二進制文件,因為我需要存儲大量數據,但只存儲某些值.當我只需要三個時,我認為沒有必要占用每個值使用八位的空間.
I have a string (it could be an integer too) in Python and I want to write it to a file. It contains only ones and zeros I want that pattern of ones and zeros to be written to a file. I want to write the binary directly because I need to store a lot of data, but only certain values. I see no need to take up the space of using eight bit per value when I only need three.
例如.假設我要將二進制字符串 "01100010"
寫入文件.如果我在文本編輯器中打開它,它會顯示 b
(01100010 是 b 的 ascii 代碼).不過不要混淆.我不想寫ascii代碼,這個例子只是為了表明我想直接將字節寫入文件.
For instance. Let's say I were to write the binary string "01100010"
to a file. If I opened it in a text editor it would say b
(01100010 is the ascii code for b). Do not be confused though. I do not want to write ascii codes, the example was just to indicate that I want to directly write bytes to the file.
澄清:
我的字符串看起來像這樣:
My string looks something like this:
binary_string = "001011010110000010010"
它不是由數字或字符的二進制代碼組成的.它包含僅與我的程序相關的數據.
It is not made of of the binary codes for numbers or characters. It contains data relative only to my program.
推薦答案
好吧,經過一番搜索,我找到了答案.我相信你們其他人根本不明白(這可能是我的錯,因為我不得不編輯兩次才能說清楚).我在這里找到了它.
Alright, after quite a bit more searching, I found an answer. I believe that the rest of you simply didn't understand (which was probably my fault, as I had to edit twice to make it clear). I found it here.
答案是將每條數據拆分,將它們轉換為二進制整數,然后將它們放入二進制數組中.之后,您可以使用數組的 tofile()
方法寫入文件.
The answer was to split up each piece of data, convert them into a binary integer then put them in a binary array. After that, you can use the array's tofile()
method to write to a file.
from array import *
bin_array = array('B')
bin_array.append(int('011',2))
bin_array.append(int('010',2))
bin_array.append(int('110',2))
with file('binary.mydata', 'wb') as f:
bin_array.tofile(f)
這篇關于將二進制整數或字符串寫入python中的文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!