程序结束后数据未保存在 pickle 中

问题描述 投票:0回答:1

我是 Python 的新手。我正在创建一个活动策划程序。共有三个列表 - 第一个包含尚未响应邀请的受邀嘉宾的姓名 (tbc_pkl)。在他们做出回应后,用户输入他们的名字,他们就会从 tbc_pickle 中删除到 confirmed_pkl 或 declined_pkl 列表中。然而,虽然程序运行时会注册确认,但它不会覆盖原始文件或永久更改列表。

我已经尝试了一切来解决这个问题,看了tuorials,在线搜索,和Chat GPT。什么都不管用。首先,我在 Python 中创建了单独的列表,然后我用 Pickle 分别保存了列表,然后我尝试在定义列表名称之前将数据保存为一个整体。

`import pickle

data = [
    ['harry potter', 'hermione granger', 'ron weasley', 'luna lovegood', 'cho chang', 'albus  
dumbledore', 'severus snape', 'sirius black', 'tom riddle'],
[],
[]
]

with open("updated_guest_lists.pkl", "wb") as f:
    pickle.dump(data, f)

with open("updated_guest_lists.pkl", "rb") as f:
    data_pkl = pickle.load(f)
    tbc_pkl, confirmed_pkl, declined_pkl = data_pkl

while True:
    user_input = input("Enter the name of person confirmed since last logged or type 'done' to exit: ")
    if user_input.strip().lower() == "done":
        break
    if user_input.strip().lower() in tbc_pkl:
        tbc_pkl.remove(user_input.strip().lower())
        confirmed_pkl.append(user_input.strip().lower())
        with open("updated_guest_lists.pkl", "wb") as f:
            pickle.dump(data, f)
            f.close()
        print("Guest confirmed. Type 'done' to exit.")
    else:
        print("Guest not found in list, please check your spelling or enter 'done' to exit.`
python list pycharm pickle
1个回答
0
投票

您的代码的问题是数据变量被用于将数据转储到文件中,而不是使用 data_pkl 变量。此外,在转储操作之前不应关闭文件句柄。

更正后的代码:

import pickle

data = [
    ['harry potter', 'hermione granger', 'ron weasley', 'luna lovegood', 'cho chang', 'albus dumbledore', 'severus snape', 'sirius black', 'tom riddle'],
    [],
    []
]

with open("updated_guest_lists.pkl", "wb") as f:
    pickle.dump(data, f)

with open("updated_guest_lists.pkl", "rb") as f:
    data_pkl = pickle.load(f)
    tbc_pkl, confirmed_pkl, declined_pkl = data_pkl

while True:
    user_input = input("Enter the name of person confirmed since last logged or type 'done' to exit: ")
    if user_input.strip().lower() == "done":
        break
    if user_input.strip().lower() in tbc_pkl:
        tbc_pkl.remove(user_input.strip().lower())
        confirmed_pkl.append(user_input.strip().lower())
        with open("updated_guest_lists.pkl", "wb") as f:
            pickle.dump(data_pkl, f)
        print("Guest confirmed. Type 'done' to exit.")
    else:
        print("Guest not found in list, please check your spelling or enter 'done' to exit.")
© www.soinside.com 2019 - 2024. All rights reserved.