easy save/load of data in python

前端 未结 7 1408
小蘑菇
小蘑菇 2020-12-28 09:35

What is the easiest way to save and load data in python, preferably in a human-readable output format?

The data I am saving/loading consists of two vectors of floats

7条回答
  •  难免孤独
    2020-12-28 09:42

    As I commented in the accepted answer, using numpy this can be done with a simple one-liner:

    Assuming you have numpy imported as np (which is common practice),

    np.savetxt('xy.txt', np.array([x, y]).T, fmt="%.3f", header="x   y")
    

    will save the data in the (optional) format and

    x, y = np.loadtxt('xy.txt', unpack=True)
    

    will load it.

    The file xy.txt will then look like:

    # x   y
    1.000 1.000
    1.500 2.250
    2.000 4.000
    2.500 6.250
    3.000 9.000
    

    Note that the format string fmt=... is optional, but if the goal is human-readability it may prove quite useful. If used, it is specified using the usual printf-like codes (In my example: floating-point number with 3 decimals).

提交回复
热议问题