How to save a list to a file and read it as a list type?

后端 未结 9 1065
既然无缘
既然无缘 2020-12-02 07:43

Say I have the list score=[1,2,3,4,5] and it gets changed whilst my program is running. How could I save it to a file so that next time the program is run I can access the c

9条回答
  •  自闭症患者
    2020-12-02 08:10

    Although the accepted answer works, you should really be using python's json module:

    import json
    
    score=[1,2,3,4,5]
    
    with open("file.json", 'w') as f:
        # indent=2 is not needed but makes the file 
        # human-readable for more complicated data
        json.dump(score, f, indent=2) 
    
    with open("file.json", 'r') as f:
        score = json.load(f)
    
    print(score)
    

    The main advantages of using a json are that:

    1. json is a widely adopted and standardized data format, so non-python programs can easily read and understand the data inside the json file.
    2. json files are human-readable.
    3. You can literally save any list/dictionary in python to a json (as long as all the contents are serializable, so most objects/functions can't be saved into a json without explicit conversion to a serializable object)

    The main disadvantages of using a json are that:

    1. The data is stored in plain-text, meaning the data is completely uncompressed, making it a slow and bloated option for large amounts of data. I wouldn't recommend storing gigabytes of vectors in a json format (hdf5 is a much better candidate for that).
    2. The contents of a list/dictionary need to be serializable (python objects need to be explicitly serialized when dumping, and then deserialized when loading).

    The json format is used for all kinds of purposes:

    • node.js uses it to track dependencies with package.json
    • many REST APIs use it to transmit and receive data
    • jsons are also a great way to store complicated nested lists/dictionaries (like an array of records).

    In general, if I want to store something I know I'm only ever going to use in the context of a python program, I typically go to pickle. If I need a platform agnostic solution, or I need to be able to inspect my data once it's stored, I go with json.

提交回复
热议问题