對象持久化(類似存檔)

現在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'])                     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章