Home:ALL Converter>Python: Read a text file and write it as a binary file

Python: Read a text file and write it as a binary file

Ask Time:2019-07-23T23:07:02         Author:Parth Bhoiwala

Json Formatter

I have a text input file with the following content:

input.feature

3   0   1   1   193:1 225:1
2   0   1   1   57:1 1005:1
4   0   1   1   467:1 7:1
5   0   1   1   619:1 259:1

I want to convert it to a binary buffer file. This is my attempt using Python:

in_file = open('input.feature', 'r', buffering=1000)
out_file = io.open('output.buffer', 'wb')

out_byte_array = bytearray(in_file.read())
out_file.write(out_byte_array)
out_file.close()

The output file I get is not a binary file, it's a text file with the same content as input file. What am I doing wrong? I also tried using BytesIO but I couldn't figure out how to write bytesIO content to a binary file. Thanks in advance.

Author:Parth Bhoiwala,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57167162/python-read-a-text-file-and-write-it-as-a-binary-file
yy