Search code examples
pythonio

easy save/load of data in python


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. Ideally, these vectors would be named in the file (e.g. X and Y).

My current save() and load() functions use file.readline(), file.write() and string-to-float conversion. There must be something better.


Solution

  • There are several options -- I don't exactly know what you like. If the two vectors have the same length, you could use numpy.savetxt() to save your vectors, say x and y, as columns:

    # saving:
    f = open("data", "w")
    f.write("# x y\n")        # column names
    numpy.savetxt(f, numpy.array([x, y]).T)
    # loading:
    x, y = numpy.loadtxt("data", unpack=True)
    

    If you are dealing with larger vectors of floats, you should probably use NumPy anyway.