对象持久化(类似存档)

现在python较为常用的3种对信息进行保存的方式:扁平文件, pickle, shelve (进行序列化保存和反序列化读取文件)

扁平文件 文本信息

scores =[88,99,77,55]

def write_scores():
    with open('data_list.txt','w',encoding='utf8') as f:
        f.write(str(scores))
    print("文件完成写入...")


def read_scores():
    with open('data_list.txt','r',encoding='utf8') as f:
        lst=eval(f.read())                         #eval 将传入字符串转化为表达式,但易错
    print(lst)

if __name__ == "__main__":
    write_scores()

pickle

pickle存储内容 存多个对象时麻烦,建议一个对象存一个文件

person = {'name' : 'Tom','age' :20}

s=pickle.dumps(person)     #序列化保存,不产生文件
s=pickle.loads(s)

pickle.dump(person,open('pickle_db','wb'))   #保存至文件
p=pickle.load(open('pickle_db','wb'))

shelve
shelve可以字典形式保留多个文件。使用较简单

import shelve

scores = [99,88,77]
student = {'name':'Mike','age':20}

db = shelve.open('shelve_student')           #打开或创建文件
db['s']=student
db['scores'] = scores
len(db)                                     #获取长度
db.close()                                  #关闭流

del(db['scores'])                     
发布了19 篇原创文章 · 获赞 0 · 访问量 556

猜你喜欢

转载自blog.csdn.net/lsy666aaa/article/details/104175043