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

2024-10-01 07:51:13 发布

您现在位置: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()

Tags: or文件thetoyouadd列表input
3条回答

对于列表中的项目: 文件.写入(项)

你应该看看这篇文章了解更多信息: Writing a list to a file with Python

您可以pickle列表:

import pickle

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

从文件加载列表:

^{pr2}$

如果要检查是否已将其保存到文件:

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

然后,在代码末尾,首次pickle列表,否则更新:

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

Padraic的答案是可行的,它是解决在磁盘上存储Python对象状态的一个很好的通用解决方案,但是在这个特定的例子中Pickle有点过头了,更不用说您可能希望这个文件是人类可读的。在

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

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

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

“with”语句只是确保文件在处理完后被适当地关闭。file关键字param to print()只是让print语句有点“假装”给它的对象系统标准输出;这适用于多种情况,例如本例中的文件句柄。在

现在,如果你想重读一遍,你可以这样做:

^{pr2}$

那会把你的原始名单还给你。结构分裂切掉被调用的字符串,这样就可以得到原始字符串的子字符串列表,每次它看到您作为参数传入的字符时,就会将其拆分。在

相关问题 更多 >