python - 使用 pickle 保存修改后的列表时出现问题

标签 python function pickle python-3.6

我要求用户将一个项目添加到列表中,然后保存修改后的列表。但是当我再次运行该程序时,之前添加的元素就消失了。我不明白为什么新元素只是暂时保存,而我的列表会自行重置。有人可以解释并建议我如何保存新项目吗?

import pickle

my_list = ["a", "b", "c", "d", "e"]

def add(item):
    my_list.append(item)
    with open("my_list.pickle", 'wb') as file:
        pickle.dump(my_list, file)
        return my_list


while True:
    item = input("Add to the list: \n").upper()
    if item == "Q":
        break
    else:
        item = add(item)

with open("my_list.pickle", "rb") as file1:
    my_items = pickle.load(file1)

print(my_items)

最佳答案

您在填充数据后从文件中读取列表。因此,如果我们分析 main(我删除了 add 函数,并注释了程序),我们得到:

# the standard value of the list
my_list = ["a", "b", "c", "d", "e"]

# adding data to the list
while True:
    # we write the new list to the file
    item = input("Add to the list: \n").upper()
    if item == "Q":
        break
    else:
        item = add(item)

# loading the list we overrided in this program session
with open("my_list.pickle", "rb") as file1:
    my_items = pickle.load(file1)

# print the loaded list
print(my_items)

因此,由于您从默认列表开始,并且每次向文件添加元素时都会重写文件,如果您在程序末尾加载列表,您猜怎么着?您将获得刚刚保存的列表。

解决方案是将加载移至程序顶部:

import pickle
<b>import os.path</b>
# the standard value of the list
my_list = ["a", "b", "c", "d", "e"]

# in case the file already exists, we use that list
<b>if os.path.isfile("my_list.pickle"):
    with open("my_list.pickle", "rb") as file1:
        my_items = pickle.load(file1)</b>

# adding data to the list
while True:
    # we write the new list to the file
    item = input("Add to the list: \n").upper()
    if item == "Q":
        break
    else:
        item = add(item)

# print the final list
print(my_items)

请注意,每次存储新列表的效率相当低。您最好让用户有机会更改列表,并将其存储在程序末尾。

关于python - 使用 pickle 保存修改后的列表时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47500793/

相关文章:

python - 在 while 循环中出现语法错误

python - DragonFly - 没有外部应用程序?

python - 运行时错误 : DataLoader worker exited unexpectedly

php:在 "echo"内部执行数学运算。还将变量名传递给函数

python - 取消 pickle 错误: Invalid load key'(heart)'

python:拉伸(stretch)世界地图

javascript - 将 javascript 数组传递给 onclick 属性的函数

javascript - 如何结合 IF 语句使用 Math.random 函数

python - 尝试编写 cPickle 对象但得到 'write' 属性类型错误

python - PyObjC:如何使用 NSCoding 来实现 python pickling?