3

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)

1

2 Answers 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)
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.