Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python read binary file
#4
Looks like at least partly you have a byte string. When printed by default, if the byte maps to an ASCII character (like \x20), then it prints that character. \x20 is a space, so the 20s are removed and replaced with spaces in your printout.

If you just need the hex values, you could use (among other things) the hex method.

>>> b = b'\x14\x02\x01\x00\x20\x00\x00\x00\x03\x18\x90\x42\x57\x23\x08\x00\x57\x23\x08\x00'
>>> b
b'\x14\x02\x01\x00 \x00\x00\x00\x03\x18\x90BW#\x08\x00W#\x08\x00'
>>> b.hex()
'1402010020000000031890425723080057230800'
If you want the specific format, you could split it up and add the "\x" in front.

>>> h = b.hex()
>>> print("".join([f"\\x{h[i:i+2]}" for i,_ in enumerate(h[::2])]))
\x14\x40\x02\x20\x01\x10\x00\x02\x20\x00\x00\x00\x00\x00\x00\x00\x03\x31\x18\x89
Reply


Messages In This Thread
python read binary file - by Pyguys - Jul-09-2020, 10:45 PM
RE: python read binary file - by Pyguys - Jul-12-2020, 01:04 AM
RE: python read binary file - by bowlofred - Jul-12-2020, 03:14 AM
RE: python read binary file - by bowlofred - Jul-12-2020, 05:32 AM
RE: python read binary file - by Pyguys - Jul-13-2020, 02:34 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 288 May-03-2024, 07:23 AM
Last Post: Pedroski55
  Recommended way to read/create PDF file? Winfried 3 2,984 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,626 Nov-09-2023, 10:56 AM
Last Post: mg24
  Python Code for Preorder Traversal of a Binary Tree Bolt 1 642 Sep-22-2023, 09:32 AM
Last Post: Gribouillis
  read file txt on my pc to telegram bot api Tupa 0 1,186 Jul-06-2023, 01:52 AM
Last Post: Tupa
  parse/read from file seperated by dots giovanne 5 1,173 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 1,433 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  How do I read and write a binary file in Python? blackears 6 7,331 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Read csv file with inconsistent delimiter gracenz 2 1,254 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Read text file, modify it then write back Pavel_47 5 1,717 Feb-18-2023, 02:49 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020