我在Python中有一串由 1 和 0 组成的字符串,我想将其写入二进制文件。我正在寻找一个好的方法来完成这个任务。
是否有标准的方法可以做到这一点,只是我不知道而已?
我在Python中有一串由 1 和 0 组成的字符串,我想将其写入二进制文件。我正在寻找一个好的方法来完成这个任务。
是否有标准的方法可以做到这一点,只是我不知道而已?
>>> 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
�+$
In [1]: int('10011001',2)
Out[1]: 153
将输入按8位分成多个部分,然后应用 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)))
open(..., 'wb')
)了吗? - liori现在有一个位字符串模块可以满足你的需求。
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的shell中使用xxd -b file.bin
来进行测试。
或者你可以像这样使用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()
$
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)