How to open and read a binary file in Python?

北城余情 提交于 2020-01-07 09:58:48

问题


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



回答3:


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.



来源:https://stackoverflow.com/questions/35000687/how-to-open-and-read-a-binary-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!