如何使用python将列表保存到文件?

0 python

我想知道如何保存用户输入的列表。我想知道如何将其保存到文件中。当我运行程序时,它说我必须使用一个字符串来写入它。那么,有没有办法将列表分配给文件,或者更好的是每次程序运行时它都会自动更新文件上的列表?如果文件最好是 .txt,那就太好了。

stuffToDo = "Stuff To Do.txt"
WRITE = "a"
dayToDaylist = []
show = input("would you like to view the list yes or no")
if show == "yes":
    print(dayToDaylist)

add = input("would you like to add anything to the list yes or no")
if add == "yes":
    amount=int(input("how much stuff would you like to add"))
    for number in range (amount):
        stuff=input("what item would you like to add 1 at a time")
        dayToDaylist.append(stuff)
remove = input("would you like to remove anything to the list yes or no")
    if add == "yes":        
    amountRemoved=int(input("how much stuff would you like to remove"))
    for numberremoved in range (amountRemoved):
        stuffremoved=input("what item would you like to add 1 at a time")
        dayToDaylist.remove(stuffremoved);
print(dayToDaylist)

file = open(stuffToDo,mode = WRITE)
file.write(dayToDaylist)
file.close()
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 5

您可以腌制列表:

import pickle

with open(my_file, 'wb') as f:
    pickle.dump(dayToDaylist, f)
Run Code Online (Sandbox Code Playgroud)

要从文件加载列表:

with open(my_file, 'rb') as f:
    dayToDaylist = pickle.load( f)
Run Code Online (Sandbox Code Playgroud)

如果你想检查你是否已经腌制到文件:

import pickle
import os
if os.path.isfile("my_file.txt"): # if file exists we have already pickled a list
    with open("my_file.txt", 'rb') as f:
        dayToDaylist = pickle.load(f)
else:
    dayToDaylist  = []
Run Code Online (Sandbox Code Playgroud)

然后在您的代码末尾第一次选择列表或更新:

with open("my_file.txt", 'wb') as f:
    pickle.dump(l, f) 
Run Code Online (Sandbox Code Playgroud)

如果要查看文件内列表的内容:

import ast
import os
if os.path.isfile("my_file.txt"):
    with open("my_file.txt", 'r') as f:
        dayToDaylist = ast.literal_eval(f.read())
        print(dayToDaylist)

with open("my_file.txt", 'w') as f:
    f.write(str(l))
Run Code Online (Sandbox Code Playgroud)