2014-11-15 52 views
0

我想知道如何保存用户输入的列表。我想知道如何将它保存到文件中。当我运行该程序时,它说我必须使用一个字符串来写入它。那么,有没有办法给文件分配一个列表,甚至每次运行程序时都会更好,它会自动更新文件列表?这将是伟大的文件将理想地是一个.txt。如何使用python将列表保存到文件?

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() 
+1

你可以腌菜单 –

+0

顺便说一下,它通常更易于“硬编码”模式参数打开(),而不是更少。使用这个伪常量只是令人困惑。此外,您不需要将其作为关键字参数提供;你可以把它叫做'open(“filename”,“a”)' – Schilcote

回答

3

可以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)) 
+0

对不起,队友我真的很陌生,我已经腌制了这个列表,但是如果我打开这个文件,怎么才能读取它呢? – cizwiz

+0

你有没有使用'pickle.load'的例子? –

+0

是的,当我打开文件它仍然有列表周围的starnge章程 – cizwiz

0

Padraic的答案将工作,并且是一个gr对于将Python对象的状态存储在磁盘上的问题需要一般的解决方案,但在这个特定情况下,Pickle有点矫枉过正,更不用说你可能希望这个文件是人类可读的。

在这种情况下,您可能希望将其转储到磁盘像这样的(这是从内存,所以有可能是语法错误):

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

这将各自在给你与你的字符串文件一个单独的行,就像你将它们打印到屏幕上一样。

“with”语句只是确保文件在您完成后适当关闭。 print()的file关键字param只是让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会截取它被调用的字符串,这样你就可以得到原始的子字符串列表,每当它看到你传入的字符作为参数时就会将其拆分。