easy save/load of data in python

前端 未结 7 1398
小蘑菇
小蘑菇 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条回答
  •  猫巷女王i
    2020-12-28 10:02

    Since we're talking about a human editing the file, I assume we're talking about relatively little data.

    How about the following skeleton implementation. It simply saves the data as key=value pairs and works with lists, tuples and many other things.

        def save(fname, **kwargs):
          f = open(fname, "wt")
          for k, v in kwargs.items():
            print >>f, "%s=%s" % (k, repr(v))
          f.close()
    
        def load(fname):
          ret = {}
          for line in open(fname, "rt"):
            k, v = line.strip().split("=", 1)
            ret[k] = eval(v)
          return ret
    
        x = [1, 2, 3]
        y = [2.0, 1e15, -10.3]
        save("data.txt", x=x, y=y)
        d = load("data.txt")
        print d["x"]
        print d["y"]
    

提交回复
热议问题