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

后端 未结 9 1082
既然无缘
既然无缘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 08:21

    pickle and other serialization packages work. So does writing it to a .py file that you can then import.

    >>> score = [1,2,3,4,5]
    >>> 
    >>> with open('file.py', 'w') as f:
    ...   f.write('score = %s' % score)
    ... 
    >>> from file import score as my_list
    >>> print(my_list)
    [1, 2, 3, 4, 5]
    

提交回复
热议问题