easy save/load of data in python

前端 未结 7 1268
小蘑菇
小蘑菇 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 10:07

    The most simple way to get a human-readable output is by using a serialisation format such a JSON. Python contains a json library you can use to serialise data to and from a string. Like pickle, you can use this with an IO object to write it to a file.

    import json
    
    file = open('/usr/data/application/json-dump.json', 'w+')
    data = { "x": 12153535.232321, "y": 35234531.232322 }
    
    json.dump(data, file)
    

    If you want to get a simple string back instead of dumping it to a file, you can use json.dumps() instead:

    import json
    print json.dumps({ "x": 12153535.232321, "y": 35234531.232322 })
    

    Reading back from a file is just as easy:

    import json
    
    file = open('/usr/data/application/json-dump.json', 'r')
    print json.load(file)
    

    The json library is full-featured, so I'd recommend checking out the documentation to see what sorts of things you can do with it.

    0 讨论(0)
提交回复
热议问题