我在Python中有一個1和0的字符串,我想將它寫入二進制文件。我遇到很多麻煩,找到一個很好的方法來做到這一點。Python:1和0的字符串 - >二進制文件
有沒有一個標準的方法來做到這一點,我只是失蹤?
我在Python中有一個1和0的字符串,我想將它寫入二進制文件。我遇到很多麻煩,找到一個很好的方法來做到這一點。Python:1和0的字符串 - >二進制文件
有沒有一個標準的方法來做到這一點,我只是失蹤?
In [1]: int('10011001',2)
Out[1]: 153
分裂您輸入的八位件,然後應用int(_, 2)
和chr
,然後連接成一個字符串,並寫這個字符串的文件。
喜歡的東西...:
your_file.write(''.join(chr(int(your_input[8*k:8*k+8], 2)) for k in xrange(len(your_input)/8)))
如果你想有一個二進制文件,
>>> import struct
>>> myFile=open('binaryFoo','wb')
>>> myStr='10010101110010101'
>>> x=int(myStr,2)
>>> x
76693
>>> struct.pack('i',x)
'\x95+\x01\x00'
>>> myFile.write(struct.pack('i',x))
>>> myFile.close()
>>> quit()
$ cat binaryFoo
�+$
這是你在找什麼?
myStr的可能值的限制很低('i'格式需要-2147483648 <= number <= 2147483647)。你必須把它分解成更小的值。無論如何,問題中沒有足夠的信息來真正回答它。 –
@oxtopus,同意範圍有限。但你會建議什麼其他方式? –
@ oxtopus同意沒有足夠的信息,但我們似乎都以同樣的方式閱讀OP ... :) –
BITS_IN_BYTE = 8
chars = '00111110'
bytes = bytearray(int(chars[i:i+BITS_IN_BYTE], 2)
for i in xrange(0, len(chars), BITS_IN_BYTE))
open('filename', 'wb').write(bytes)
或者你可以使用array
模塊這樣
$ python
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random,array
#This is the best way, I could think of for coming up with an binary string of 100000
>>> binStr=''.join([str(random.randrange(0,2)) for i in range(100000)])
>>> len(binStr)
100000
>>> a = array.array("c", binStr)
#c is the type of data (character)
>>> with open("binaryFoo", "ab") as f:
... a.tofile(f)
...
#raw writing to file
>>> quit()
$
有一個比特串模塊現在該做你需要什麼。
from bitstring import BitArray
my_str = '001001111'
binary_file = open('file.bin', 'wb')
b = BitArray(bin=my_str)
b.tofile(binary_file)
binary_file.close()
您可以從Linux中的外殼採用xxd -b file.bin
中的「1」和「0」字符串測試的標準方法是從來沒有通車。這些字符串從哪裏來的? –
沒有像「二進制文件」那樣有意義的東西。所有文件都是'二進制';它們包含比特序列。它聽起來像是**你的意思是「我想將字符串中的每個'1'和'0'字符解釋爲一個單獨的位,將8位的一組組合成字節,並將結果寫入文件中。 –
@KarlKnechtel。當然,是的,這就是我想要做的。但是,當我嘗試這樣做時,我遇到了錯誤,這與liori下面提出的建議很相似。我已經在下面解釋了這個問題。 – sevandyk