Reputation: 163
I'm trying to take a file and convert it's contents to hex, save that to a file, and then convert the hex string back to ascii and save that to a file. The below method works, but adds an extra empty line after ever line in the hex to ascii file, which should be identical to the initial file...
import binascii
filename = 'file.txt'
with open(filename, 'rb') as f:
content = f.read()
out = binascii.hexlify(content)
f = open('out.txt', 'w')
f.write(out)
f.close()
asci = out.decode("hex")
w = open('printed.txt', 'w')
w.write(asci)
w.close()
==================================================================================
After actually reading the python documentation, I realized my mistake. The code should be as follows. (Slightly altered to read from the out.txt...)
import binascii
filename = 'file.txt'
with open(filename, 'rb') as f:
content = f.read()
out = binascii.hexlify(content)
f = open('out.txt', 'wb')
f.write(out)
f.close()
import binascii
filename = 'out.txt'
with open(filename, 'rb') as f:
content = f.read()
asci = content.decode("hex")
asci = out.decode("hex")
w = open('printed.txt', 'wb')
w.write(asci)
w.close()
The key was adding the appending "b" to the the "w" in the open command to have the file opened in binary write mode...
Upvotes: 1
Views: 3947
Reputation: 127
Rather than using str.decode
, you should try using binascii.unhexlify
. decode
might be doing the translation of line-breaks slightly differently, e.g. how it handles '\r\n'
vs '\n'
.
Upvotes: 1