I want to convert a bin file to txt file in python.
with open("atb.bin", "rb") as file:
data = file.read(8)
datastring = str(data)
print(datastring)
print(' '.join(str(ord(c)) for c in datastring))
The output I get is
b'\x14\x12\x1c\x1a#\x00-d'
98 39 92 120 49 52 92 120 49 50 92 120 49 99 92 120 49 97 35 92 120 48 48 45 100 39
Now, how do I convert this to decimal and store in a txt file?
-
1don't convert your bytes object to string... python 2 or python 3?Jean-François Fabre– Jean-François Fabre ♦2018年04月05日 15:23:25 +00:00Commented Apr 5, 2018 at 15:23
-
Its Python 3.Can you please suggest a solution?Aj Mv– Aj Mv2018年04月05日 15:26:08 +00:00Commented Apr 5, 2018 at 15:26
-
Possible duplicate of Reading a binary file with pythonmajin– majin2018年04月05日 15:37:20 +00:00Commented Apr 5, 2018 at 15:37
2 Answers 2
Your main mistake is doing:
datastring = str(data)
As it converts the representation of the data object to string, with b prefix and quotes, and escaping... wrong.
read your file as you're doing:
with open("atb.bin", "rb") as file:
data = file.read(8)
now data is a bytes object, no need for ord in python 3, values are already integer. Now open a text file and dump the values (converting integers to string, decimal):
with open("out.txt", "w") as f:
f.write(" ".join(map(str,data))):
f.write("\n")
In python 2 you'd need to get the character code then convert to string:
f.write(" ".join([str(ord(c)) for c in data]))
Comments
Your Python converts into text, the text representation of the 8 characters in the file.
Hence, instead of
print(' '.join(str(ord(c)) for c in datastring))
you should have put
print(' '.join(str(ord(c)) for c in data))
which you can then write to a file using standard techniques.
ie. (Python 2)
>>> data=b'\x14\x12\x1c\x1a#\x00-d'
>>> print(' '.join(str(ord(c)) for c in data))
20 18 28 26 35 0 45 100
(Python 3)
>>> data=b'\x14\x12\x1c\x1a#\x00-d'
>>> print(' '.join(str(c) for c in data))
20 18 28 26 35 0 45 100