Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

ascii - reading fortran unformatted file with python

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 array of character*1 name(80) and so on. So I start out with

f = open(filename,'rb')
bytes = 80
name = struct.unpack('c'*bytes,f.read(bytes))

and name is an 80-length tuple consisting of strings of length 1; some of the contents of which are hexadecimal strings (e.g., x00). How can I go about converting this variable to a single ascii string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...