【问题标题】:Storing list in file将列表存储在文件中
【发布时间】:2020-01-31 19:31:58
【问题描述】:

我正在使用 python 3.8 中的函数来将我的想法列表存储在 idea.txt 文件中,并在文件中获取新条目更新列表之后。由于某种原因,它仅适用于第一次进入,然后变得混乱,即: [(1, '["[\'aaa\']", \'sss\']'), (2, 'ddd')]

这是我的代码:

def add_idea():
while True:
    with open("ideas.txt","r") as f:
        updated_list = f.readlines()
        idea=input("What is your new idea?"+"\n")
        idea=str(idea)
        updated_list.append(idea)
        "\n".join(updated_list)
        f.close()
    with open("ideas.txt","w") as f:
        f.write(str(updated_list))
        f.close()
        num_list = list(enumerate(updated_list,1))
        print(num_list)

我是 python 和编程新手,所以请善待;)

【问题讨论】:

  • f.write(str(updated_list)) 不是序列化列表对象的合理方式。不要这样做。使用预定义的序列化格式,例如 jsonpickle
  • 顺便说一句,你没想到的是什么:[(1, '["[\'aaa\']", \'sss\']'), (2, 'ddd')]
  • 您无需致电f.close()。这就是 with... 块的用途。
  • 语句"\n".join(updated_list)完全没有作用 - 您从列表中生成了一个字符串,但没有存储它或以其他方式对其进行任何操作。

标签: python python-3.x list storing-data


【解决方案1】:
def add_idea():
    while (idea := input("What is your new idea?"+"\n")):
        with open("ideas.txt","a") as f:
            print(idea, file=f)

一些注意事项:

  • 使用 Walrus 运算符
  • 您不需要显式关闭文件,因为一旦超出范围就会关闭它
  • 你应该有办法退出 while/input 循环

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多