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

时间:2017-11-26 20:38:34

标签: 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)

1 个答案:

答案 0 :(得分:1)

在用数据填充后,您可以从文件中读取列表。因此,如果我们分析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
import os.path
# the standard value of the list
my_list = ["a", "b", "c", "d", "e"]

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

# 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)

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