python-持久化数据pickle

2016-12-01  本文已影响243人  望月成三人
import pickle
from common import operateFile
def write_pickle(dict_data, path="data.txt):
    read = read_pickle(path)
    result = []
    if len(read) > 0: #先读取数据,然后把读取的数据和新数据组合在一起,再写到文件
        read.append(dict_data)
        result = read
    else:
        result.append(dict_data)
    with open(path, 'wb') as f:
        print(result)
        pickle.dump(result, f, 0)

def read_pickle(path):
    data = {}
    if operateFile.OperateFile(path).check_file(): #如果文件存在
        with open(path, 'rb') as f:
            try:
                data = pickle.load(f) #数据为空报错
            except EOFError:
                pass
    print(data)
    return data
if __name__=="__main__":
    data = {"log":"132"}
    write_pickle(data, path=GetVariable.CRASH_LOG_PATH)
    read_pickle(path=GetVariable.CRASH_LOG_PATH)
    # operateFile.OperateFile(PATH("data.pickle")).remove_file() #删除文件




上一篇下一篇

猜你喜欢

热点阅读