美文网首页
python-持久化数据pickle

python-持久化数据pickle

作者: 望月成三人 | 来源:发表于2016-12-01 15:39 被阅读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() #删除文件
    
    
    
    
    

    相关文章

      网友评论

          本文标题:python-持久化数据pickle

          本文链接:https://www.haomeiwen.com/subject/mswxmttx.html