在Python中将文本文件保存为二进制文件

3
我要如何生成一个将被保存为二进制文件的文本文件?据说需要是二进制格式才能在Web控制器(odoo)中调用该文件。

阅读此链接:https://dev59.com/BGMk5IYBdhLWcg3w8ieC - undefined
2个回答

4
# 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)

2
我还有一个任务,需要一个二进制模式下的文本数据文件。没有1和0,只是数据“以二进制模式获取字节对象”。

当我尝试上面的建议时,使用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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接