問題描述
我發現用 Python 讀取二進制文件特別困難.你能幫我個忙嗎?我需要閱讀這個文件,它在 Fortran 90 中很容易被閱讀
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 n_particles, n_groups
real*4 group_id(n_particles)
read (*) n_particles, n_groups
read (*) (group_id(j),j=1,n_particles)
具體來說,文件格式是:
In detail, the file format is:
Bytes 1-4 -- The integer 8.
Bytes 5-8 -- The number of particles, N.
Bytes 9-12 -- The number of groups.
Bytes 13-16 -- The integer 8.
Bytes 17-20 -- The integer 4*N.
Next many bytes -- The group ID numbers for all the particles.
Last 4 bytes -- The integer 4*N.
如何使用 Python 閱讀此內容?我嘗試了一切,但從未奏效.我有沒有機會在 python 中使用 f90 程序,讀取這個二進制文件,然后保存我需要使用的數據?
How can I read this with Python? I tried everything but it never worked. Is there any chance I might use a f90 program in python, reading this binary file and then save the data that I need to use?
推薦答案
讀取二進制文件內容如下:
Read the binary file content like this:
with open(fileName, mode='rb') as file: # b is important -> binary
fileContent = file.read()
然后使用struct.unpack解壓"二進制數據:
then "unpack" binary data using struct.unpack:
起始字節:struct.unpack("iiiiii", fileContent[:20])
正文:忽略標題字節和尾隨字節(= 24);剩下的部分構成正文,要知道正文中的字節數,進行整數除以 4;得到的商乘以字符串 'i'
為 unpack 方法創建正確的格式:
The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string 'i'
to create the correct format for the unpack method:
struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])
結束字節:struct.unpack("i", fileContent[-4:])
這篇關于用python讀取二進制文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!