[英]Save txt file as binary in python
How do I generate a txt file that will be saved as binary file.如何生成将保存为二进制文件的 txt 文件。 it is said that it is needed to be a binary to call the file in web controller(odoo)
据说在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)
I also had a task where I needed a file with text data in binary mode.我还有一个任务,我需要一个包含二进制模式文本数据的文件。 No 1s and 0s, just data 'in binary mode to obtain a bytes object.'
没有 1 和 0,只是“以二进制模式获取字节对象”的数据。
When I tried the suggestion above, with binarray = ' '.join(format(ch, 'b') for ch in bytearray(mytextstring))
, even after specifying the mandatory encoding=
for bytearray()
, I got an error saying that binarray
was a string, so it could not be written in binary format (using the 'wb'
or 'br+'
modes for open()
).当我尝试上面的建议时,使用
binarray = ' '.join(format(ch, 'b') for ch in bytearray(mytextstring))
,即使在为bytearray()
指定了强制encoding=
之后,我也收到一条错误消息binarray
是一个字符串,因此它不能以二进制格式写入(使用open()
的'wb'
或'br+'
模式)。
Then I went to the Python bible and read:然后我去看了 Python 圣经并阅读了:
bytearray() then converts the string to bytes using
str.encode()
.bytearray() 然后使用
str.encode()
将字符串转换为字节。
So I noticed that all I really needed was str.encode()
to get a byte object.所以我注意到我真正需要的是
str.encode()
来获取一个字节对象。 Problem solved!问题解决了!
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.