Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : read array in binary file

I am currently trying to read an fortran file with python with the following technique

with open(myfile, "rb") as f:
    for i in range (0, n):
        s = struct.unpack('=f', f.read(4))
        mylist.append(s[0])

But it is very slow for large arrays. Is there a way to read the content of the entire loop in one time and put it to mylist in order to avoid a conversion/append of each item one by one?

Thank you very much.

like image 586
Vincent Avatar asked Oct 20 '25 14:10

Vincent


1 Answers

This is what the array module is for:

a = array.array('f')
a.fromfile(f, n)

Now you can use the array object like a normal sequence type. You can also convert it to a list if you need to with tolist.

like image 145
interjay Avatar answered Oct 22 '25 03:10

interjay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!