我要如何生成一个将被保存为二进制文件的文本文件?据说需要是二进制格式才能在Web控制器(odoo)中调用该文件。
# read textfile into string
with open('mytxtfile.txt', 'r') as txtfile:
mytextstring = txtfile.read()
# change text into a binary array
binarray = ' '.join(format(ch, 'b') for ch in bytearray(mytextstring))
# save the file
with open('binfileName', 'br+') as binfile:
binfile.write(binarray)
当我尝试上面的建议时,使用binarray =''.join(format(ch,'b') for ch in bytearray(mytextstring))
,即使指定了bytearray()
的必需encoding =
,我仍然会收到一个错误,说binarray
是一个字符串,因此无法以二进制格式写入(使用'wb'
或'br +'
模式进行open()
)。
然后我去看了Python圣经:
bytearray()
然后使用str.encode()
将字符串转换为字节。
所以我注意到,我真正需要的只是str.encode()
来获得一个字节对象。问题解决了!
filename = "/path/to/file/filename.txt"
# read file as string:
f = open(filename, 'r')
mytext = f.read()
# change text into binary mode:
binarytxt = str.encode(mytext)
# save the bytes object
with open('filename_bytes.txt', 'wb') as fbinary:
fbinary.write(binarytxt)