4

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?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Aj Mv
  • 43
  • 1
  • 1
  • 3

2 Answers2

3

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]))
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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
MikeW
  • 5,504
  • 1
  • 34
  • 29