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

时间:2014-11-15 22:51:28

标签: 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()

3 个答案:

答案 0 :(得分:4)

您可以pickle列表:

import pickle

with open(my_file, 'wb') as f:
    pickle.dump(dayToDaylist, f)

从文件中加载列表:

with open(my_file, 'rb') as f:
    dayToDaylist = pickle.load( f)

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

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  = []

然后在你的代码结束时第一次选择列表或者更新:

with open("my_file.txt", 'wb') as f:
    pickle.dump(l, f) 

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

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))

答案 1 :(得分:0)

列表中的项目:     file.write(项目)

您应该查看此帖子了解更多信息: Writing a list to a file with Python

答案 2 :(得分:0)

Padraic的答案是有效的,并且是解决在Python上存储Python对象状态的一个很好的通用解决方案,但在这种特殊情况下,Pickle有点矫枉过正,更不用说你的事实了可能希望这个文件是人类可读的。

在这种情况下,您可能希望将其转储到磁盘上(这是来自内存,因此可能存在语法错误):

with open("list.txt","wt") as file:
    for thestring in mylist:
        print(thestring, file=file)

这将为您提供一个文件,其中每个字符串都在一个单独的行上,就像您将它们打印到屏幕上一样。

" with"语句只是确保文件在您完成后正确关闭。 print()的文件关键字参数只是使print语句排序为"假装"你给它的对象是sys.stdout;这适用于各种各样的事情,例如在这种情况下文件句柄。

现在,如果你想重读它,你可能会这样做:

with open("list.txt","rt") as file:
    #This grabs the entire file as a string
    filestr=file.read()
mylist=filestr.split("\n")

那会给你原来的清单。 str.split删除它被调用的字符串,这样你就可以得到一个原始子字符串列表,每当它看到你作为参数传入的字符时就将其拆分。