How to save a double file in python?

Let's say I need to save a matrix (each row corresponds to one row), which can later be loaded from fortran. Which method should I prefer? Is converting everything to string the only approach?

+3
source share
4 answers

You can also save them in binary format. See the documentation on the standard module struct, it has a function packto convert a Python object to binary data.

For example:

import struct

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

. Fortran . , , :

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

, 'd' * len(matrix_row) , .

+6

fortran, , .

, ( "" ), ( struct ..). , , .

, , , (endianity, default double sizes).
, (, , , ), , , .

+2

JSON

import json
matrix = [[2.3452452435, 3.34134], [4.5, 7.9]]
data = json.dumps(matrix)
open('file.ext', 'wb').write(data)

:

[[2.3452452435, 3.3413400000000002], [4.5, 7.9000000000000004]]
+1

( ), Fortran , , ( - READ (FILE_ID, '2 (F) '), ):

1.234  5.6789e4
3.1415 9.265358978
42     ...

Python .

+1

Source: https://habr.com/ru/post/1724010/


All Articles