【问题标题】:How do I save a list to file using python? [duplicate]如何使用 python 将列表保存到文件? [复制]
【发布时间】: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


【解决方案1】:

你可以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))

【讨论】:

  • 对不起,伙计,我真的很陌生,我已经腌制了列表,但是如果我打开文件,如何才能读取它?
  • 你用过pickle.load这个例子吗?
  • 是的,当我打开文件时,列表中仍然有starnge章程
  • 您要重复使用该列表还是在文件中查看它?您的问题似乎只想重复使用列表
  • 好的,我会添加另一种方式
【解决方案2】:

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

您应该查看这篇文章以获取更多信息: Writing a list to a file with Python

【讨论】:

    【解决方案3】:

    Padraic 的答案会起作用,并且是解决将 Python 对象的状态存储在磁盘上的问题的一个很好的通用解决方案,但在这种特定情况下,Pickle 有点矫枉过正,更不用说你可能想要这个文件的事实是人类可读的。

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

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

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

    “with”语句只是确保文件在您完成后正确关闭。 print() 的 file 关键字参数只是让 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 将被调用的字符串切碎,以便您获得原始子字符串的列表,并在每次看到您作为参数传入的字符时将其拆分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 2021-07-04
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多