Reading a binary file with python

后端 未结 6 1464
天涯浪人
天涯浪人 2020-11-27 12:12

I find particularly difficult reading binary file with Python. Can you give me a hand? I need to read this file, which in Fortran 90 is easily read by

int*4          


        
6条回答
  •  暖寄归人
    2020-11-27 12:50

    To read a binary file to a bytes object:

    from pathlib import Path
    data = Path('/path/to/file').read_bytes()  # Python 3.5+
    

    To create an int from bytes 0-3 of the data:

    i = int.from_bytes(data[:4], byteorder='little', signed=False)
    

    To unpack multiple ints from the data:

    import struct
    ints = struct.unpack('iiii', data[:16])
    
    • pathlib
    • int.from_bytes()
    • struct

提交回复
热议问题