How to open and read a binary file in Python?

2019-03-07 08:56发布

问题:

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.

回答1:

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())


回答2:

Here is an Exmaple: See if this helps and let me know

with open('somefile.bin', 'rb') as f:#the second paramenter "rb"is used only when reading Binary Files. Term "rb" stands for Read binary
data = f.read() # in here we are assigning a variable which will read whatever in the file and it will be stored in the variable called "Data"
print(data)