How do I generate a txt file that will be saved as binary file. it is said that it is needed to be a binary to call the file in web controller(odoo)
Asked
Active
Viewed 1.1k times
2
-
read this https://stackoverflow.com/questions/18815820/convert-string-to-binary-in-python – Mauricio Cortazar Aug 31 '17 at 06:10
2 Answers
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)

Community
- 1
- 1

yacov mosbacher
- 43
- 2
2
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.'
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()
).
Then I went to the Python bible and read:
bytearray() then converts the string to bytes using
str.encode()
.
So I noticed that all I really needed was str.encode()
to get a byte object. 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)

Ovi Oprea
- 131
- 2
- 5