reading fortran unformatted file with python

后端 未结 2 1894
广开言路
广开言路 2020-12-22 02:08

I have a fortran program generating unformatted files and I am trying to read them into Python.

I have the source code so I know the first \"chunk\" is a character a

相关标签:
2条回答
  • 2020-12-22 03:01

    Use the correct format specifier in the first place, then strip off the NULs.

    >>> struct.unpack('%ds' % 20, 'Hello, World!' + '\x00' * 7)
    ('Hello, World!\x00\x00\x00\x00\x00\x00\x00',)
    >>> struct.unpack('%ds' % 20, 'Hello, World!' + '\x00' * 7)[0].rstrip('\x00')
    'Hello, World!'
    
    0 讨论(0)
  • 2020-12-22 03:06

    Most Fortran unformatted files will contain extra bytes to specify the length of the record. A record is the group of items written with a single Fortran write statement. Typically 4-bytes at the beginning and end of each record. So in another language you will want to read these "hidden" values and skip them. In this case, if you try to interpret them as part of your string, you will add incorrect values to the string, which will likely have peculiar values for ASCII.

    A Fortran string will be fixed length and padded on the end with blanks, which is 0x20 in ASCII. I would not expect the value 0x00 unless the string was not initialized or the Fortran programmer was using a string to hold binary data.

    In this era, if a Fortran programmer is writing an unformatted/binary file that is intended for use with another language, they can cause these extra bytes to be omitted by using the "stream" IO method of Fortran 2003.

    0 讨论(0)
提交回复
热议问题