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

Issue with saving a modified list with pickle

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

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)

请注意,每次都存储新列表效率很低。您最好让用户有机会更改列表,并将其存储在程序结束时。