I was able to find a solution and to write a whole new file using bytes. The problem is all about the code used to represent the string: while trying to write a bit string (i.e. "101010111000") I was actually writing its ASCII value in a text file.
what you need to do it:
- take every 8 characters of the string
- convert those characters in int
- cast the result to end up with bytes (I casted a whole list)
- profit
The code I used is the following:
"""Reads file as binary string"""
def openFileBinary(file):
fileBin = ""
bytes = bytearray(open(file, "rb").read())
for i in bytes:
fileBin = fileBin + str(('{:08b}'.format(i)))
return fileBin
"""Writes string to file as binary"""
def writeFile(stream):
with open("output", "wb") as f:
f.write(bitstring_to_bytes(stream))
"""Converts binary string into bytes"""
def bitstring_to_bytes(s):
b = bytearray()
w = [int(s[i:i+8],2) for i in range(0, len(s), 8)]
return(bytes(w))