Python pickle 模块使用

Python pickle module usage

import pickle

data_list = list()

def Add(x):
    data_list.append(x)
    with open("data.pkl", "wb") as f:
        pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL)

while 1:
    abc = input("--->")
    if abc == "data":
        with open("data.pkl", "rb") as f:
            print(pickle.load(f))
    else:  
        Add(abc)
        print(data_list)
        

我用 pickle 模块保存了我的列表。 重启程序后,如果不添加新数据查询列表内容,可以看到记录,但是如果添加新数据,就看不到旧记录了。为什么我看不到旧记录?

这是因为您使用空列表启动程序。如果在启动时存在,你应该添加一个同步数据库的功能

import os
import pickle

# Sync database
if os.path.exists('data.pkl'):
    with open("data.pkl", "rb") as f:
        data_list = pickle.load(f)
else:
    data_list = list()

def Add(x):
    data_list.append(x)
    with open("data.pkl", "wb") as f:
        pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL)

while 1:
    abc = input("--->")
    if abc == "data":
        with open("data.pkl", "rb") as f:
            print(pickle.load(f))
    else:  
        Add(abc)
        print(data_list)