Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save double to file in python?

Let's say I need to save a matrix(each line corresponds one row) that could be loaded from fortran later. What method should I prefer? Is converting everything to string is the only one approach?

like image 644
hahahaha Avatar asked Sep 13 '26 23:09

hahahaha


1 Answers

You can save them in binary format as well. Please see the documentation on the struct standard module, it has a pack function for converting Python object into binary data.

For example:

import struct

value = 3.141592654
data = struct.pack('d', value)
open('file.ext', 'wb').write(data)

You can convert each element of your matrix and write to a file. Fortran should be able to load that binary data. You can speed up the process by converting a row as a whole, like this:

row_data = struct.pack('d' * len(matrix_row), *matrix_row)

Please note, that 'd' * len(matrix_row) is a constant for your matrix size, so you need to calculate that format string only once.

like image 75
fviktor Avatar answered Sep 16 '26 13:09

fviktor



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!