【问题标题】:How can I use pickle in python 3 to create a save function如何在 python 3 中使用 pickle 创建保存功能
【发布时间】:2017-05-13 07:40:28
【问题描述】:

我的代码只是一个测试,因此我可以了解 pickle 的工作原理。有一个用户可以添加项目的单词列表。我想将单词添加到列表中,以便当程序再次运行时,列表将包含用户的单词。我不明白怎么做,因为你首先要定义列表,所以我最终得到了原始单词加上用户在程序运行中写的单词

    import pickle

    class info():
        words = ['skylight','revenue']

    item = input("Type a word: ")
    info.words.append(item)

    with open("savefile.pickle","wb") as handle:
        pickle.dump(info.words, handle)

    with open("savefile.pickle","rb") as handle:
        info.words = pickle.load(handle)

    print(info.words)

【问题讨论】:

    标签: python python-3.x pickle


    【解决方案1】:

    嗯,您需要一种方法来区分第一次和第二次运行。我建议检查保存文件是否存在。如果是这样,您可以加载泡菜。否则,您将使用“默认值”。

    您现在拥有的是在保存后立即加载泡菜。没有意义。

    您可以使用os.path.isfile 来判断文件是否存在。

    import pickle
    import os.path
    
    class info():
        words = ['skylight','revenue']
    
    if os.path.isfile("savefile.pickle"):
        with open("savefile.pickle","rb") as handle:
            info.words = pickle.load(handle)
    
    item = input("Type a word: ")
    info.words.append(item)
    
    with open("savefile.pickle","wb") as handle:
        pickle.dump(info.words, handle)
    
    print(info.words)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2020-08-29
      相关资源
      最近更新 更多