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

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

    I decided I didn't want to use a pickle because I wanted to be able to open the text file and change its contents easily during testing. Therefore, I did this:

    score = [1,2,3,4,5]
    
    with open("file.txt", "w") as f:
        for s in score:
            f.write(str(s) +"\n")
    
    with open("file.txt", "r") as f:
      for line in f:
        score.append(int(line.strip()))
    

    So the items in the file are read as integers, despite being stored to the file as strings.

提交回复
热议问题