JDee
JDee

Reputation: 65

Save txt file as binary in python

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)

Upvotes: 3

Views: 13287

Answers (2)

Ovi Oprea
Ovi Oprea

Reputation: 151

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)

Upvotes: 2

yacov mosbacher
yacov mosbacher

Reputation: 43

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

Upvotes: 4

Related Questions