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

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

    What I did not like with many answers is that it makes way too many system calls by writing to the file line per line. Imho it is best to join list with '\n' (line return) and then write it only once to the file:

    mylist = ["abc", "def", "ghi"]
    myfile = "file.txt"
    with open(myfile, 'w') as f:
        f.write("\n".join(mylist))
    

    and then to open it and get your list again:

    with open(myfile, 'r') as f:
        mystring = f.read()
    my_list = mystring.split("\n")
    

提交回复
热议问题