用python读取fortran未格式化的文件 [英] reading fortran unformatted file with python

查看:188
本文介绍了用python读取fortran未格式化的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有源代码,所以我知道第一个块是一个字符* 1名称(80)等字符数组。所以我从
$ b

  f = open(文件名,'rb')
字节= 80
name = struct.unpack('c'* bytes,f.read(bytes))

name 是长度为80的长元组,由长度为1的字符串组成;其中的一些内容是十六进制字符串(例如, \x00 )。

解决方案

大多数Fortran未格式化的文件都会包含额外的字节来指定这个字符串记录的长度。记录是用一个Fortran写入语句编写的一组项目。通常每个记录的开头和结尾都有4个字节。所以在另一种语言中,您会想要阅读这些隐藏的值并跳过它们。在这种情况下,如果您尝试将它们解释为字符串的一部分,则会向字符串添加不正确的值,这可能会为ASCII提供特殊值。



A Fortran字符串的长度是固定的,最后用空格填充,这是ASCII码中的0x20。我不希望值为0x00,除非该字符串未初始化或者Fortran程序员使用字符串来保存二进制数据。



在这个时代,如果Fortran程序员是编写旨在与其他语言一起使用的未格式化/二进制文件,则可以使用Fortran 2003的streamIO方法来省略这些额外的字节。


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?

解决方案

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.

这篇关于用python读取fortran未格式化的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆