问题描述
我有一个生成无格式文件的 fortran 程序,我正在尝试将它们读入 Python.
I have a fortran program generating unformatted files and I am trying to read them into Python.
我有源代码,所以我知道第一个块"是 character*1 name(80)
的字符数组,依此类推.所以我从
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
是一个长度为 80 的元组,由长度为 1 的字符串组成;其中一些内容是十六进制字符串(例如,x00
).如何将此变量转换为单个 ascii 字符串?
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?
推荐答案
大多数 Fortran 无格式文件会包含额外的字节来指定记录的长度.记录是使用单个 Fortran 写入语句写入的一组项目.通常在每条记录的开头和结尾有 4 个字节.因此,在另一种语言中,您将需要阅读这些隐藏"值并跳过它们.在这种情况下,如果您尝试将它们解释为字符串的一部分,则会在字符串中添加不正确的值,这些值很可能具有特殊的 ASCII 值.
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.
Fortran 字符串将是固定长度并在末尾用空格填充,即 ASCII 中的 0x20.除非字符串未初始化或 Fortran 程序员使用字符串来保存二进制数据,否则我不会期望值 0x00.
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.
在这个时代,如果 Fortran 程序员正在编写一个旨在与另一种语言一起使用的未格式化/二进制文件,他们可以通过使用 Fortran 2003 的流"IO 方法来省略这些额外的字节.
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.
这篇关于用python读取fortran无格式文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!