【发布时间】:2015-01-13 03:00:12
【问题描述】:
我想知道如何保存用户输入的列表。我想知道如何将其保存到文件中。当我运行程序时,它说我必须使用一个字符串来写入它。那么,有没有办法将列表分配给文件,或者更好的是每次程序运行时它都会自动更新文件上的列表?最好的文件是 .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()
【问题讨论】:
-
你可以腌制列表
-
顺便说一下,将 mode 参数“硬编码”到 open() 通常更具可读性,而不是更少。使用那个伪常数只是令人困惑。此外,您不需要将其作为关键字参数提供;你可以直接称它为
open("filename", "a")
标签: python