5

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
141k24 gold badges179 silver badges246 bronze badges
asked Apr 5, 2018 at 15:21
3
  • 1
    don't convert your bytes object to string... python 2 or python 3? Commented Apr 5, 2018 at 15:23
  • Its Python 3.Can you please suggest a solution? Commented Apr 5, 2018 at 15:26
  • Possible duplicate of Reading a binary file with python Commented Apr 5, 2018 at 15:37

2 Answers 2

4

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]))
answered Apr 5, 2018 at 15:28
Sign up to request clarification or add additional context in comments.

Comments

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
answered Apr 5, 2018 at 15:32

1 Comment

Can we use struct.unpack() in this case? In which scenarios the unpack is useful?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.