-4

I have a binary file (link) that I would like to open and read contents of with Python. How are such binary files opened and read with Python? Any specific modules to use for such an operation.

Tom Kurushingal
  • 6,086
  • 20
  • 54
  • 86
  • 4
    This is something that can be found with a simple google search and so doesn't fit on SO. Look up 'file open python' – TankorSmash Jan 25 '16 at 19:31
  • 2
    I assume you HAVE read the python manual or/and googled. So what is unclear in the information you gained? – Psytho Jan 25 '16 at 19:32
  • Look into the `struct` module. – Colin Basnett Jan 25 '16 at 19:35
  • Possible duplicate of [Difference between parsing a text file in r and rb mode](https://stackoverflow.com/q/9644110/608639), [Reading a binary file with python](https://stackoverflow.com/q/8710456/608639) – jww Apr 23 '18 at 04:06

3 Answers3

4

The 'b' flag will get python to treat the file as a binary, so no modules are needed. Also you haven't provided a purpose for having python read a binary file with a question like that.

f = open('binaryfile', 'rb')
print(f.read())
ZetaRift
  • 332
  • 1
  • 9
1

Here is an Example:

with open('somefile.bin', 'rb') as f: #the second parameter "rb" is used only when reading binary files. Term "rb" stands for "read binary".
data = f.read() #we are assigning a variable which will read whatever in the file and it will be stored in the variable called data.
print(data)
ShellZero
  • 4,415
  • 12
  • 38
  • 56
hameed
  • 87
  • 1
  • 1
  • 7
1

Reading a file in python is trivial (as mentioned above); however, it turns out that if you want to read a binary file and decode it correctly you need to know how it was encoded in the first place.

I found a helpful example that provided some insight at https://www.devdungeon.com/content/working-binary-data-python,

# Binary to Text
binary_data = b'I am text.'
text = binary_data.decode('utf-8') #Trans form back into human-readable ASCII
print(text)

binary_data = bytes([65, 66, 67])  # ASCII values for A, B, C
text = binary_data.decode('utf-8')
print(text)

but I was still unable to decode some files that my work created because they used an unknown encoding method.

Once you know how it is encoded you can read the file bit by bit and perform the decoding with a function of three.

FunnyHarry
  • 31
  • 6