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

后端 未结 9 1084
既然无缘
既然无缘 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:09

    You can use pickle module for that. This module have two methods,

    1. Pickling(dump): Convert Python objects into string representation.
    2. Unpickling(load): Retrieving original objects from stored string representstion.

    https://docs.python.org/3.3/library/pickle.html

    Code:

    >>> import pickle
    >>> l = [1,2,3,4]
    >>> with open("test.txt", "wb") as fp:   #Pickling
    ...   pickle.dump(l, fp)
    ... 
    >>> with open("test.txt", "rb") as fp:   # Unpickling
    ...   b = pickle.load(fp)
    ... 
    >>> b
    [1, 2, 3, 4]
    

    Also Json

    1. dump/dumps: Serialize
    2. load/loads: Deserialize

    https://docs.python.org/3/library/json.html

    Code:

    >>> import json
    >>> with open("test.txt", "w") as fp:
    ...     json.dump(l, fp)
    ...
    >>> with open("test.txt", "r") as fp:
    ...     b = json.load(fp)
    ...
    >>> b
    [1, 2, 3, 4]
    

提交回复
热议问题