python 物件持久化

2021-08-20 05:15:12 字數 1059 閱讀 9980

print(open('persondb.dat','rb').read())

testdemo2.py

#讀取資料庫

#載入乙個例項的時候,類極其模組的檔案都必須匯入

#該類的例項再次載入的時候,對類的源**檔案的修改會自動選取

import testdemo

import shelve

db=shelve.open('persondb')

print(len(db))    #獲取資料條數 3

print(list(db.keys()))   #獲取資料鍵值 ['bob smith', 'sue jones', 'tom jones']

tom=db['tom jones']

print(tom)    #[manager: job=mgr, name=tom jones, pay=50000]

print(tom.lastname())    #jones

print(tom.pay)     #50000

for key in db.keys():

print(key, '=>', db[key])   #列印資料庫中所有資料

for key in sorted(db, reverse=true):

print(key, '=>', db[key])   #列印資料庫中所有資料,並且排序

db.close()

testdemo3.py

#更新shelve中的物件

import shelve

db=shelve.open('persondb')

sue=db['sue jones']

print(sue)    #[person: job=dev, name=sue jones, pay=10000],每次執行值都會儲存

sue.giveraist(1.1)

db['sue jones']=sue

print(sue)    #[person: job=dev, name=sue jones, pay=21000]   pay為最新的值,每次執行值都會變化

db.close()

python物件持久化

pickle模組 import pickle person s pickle.dumps person p pickle.loads s pickle.dump person,open pickle db wb p pickle.load open pickle db rb print p prin...

python持久化物件

通過shelve模組即可持久化物件 import shelve import numpy as np def writeobj name,obj with shelve.open object as db db name obj def readobj name try with shelve.op...

物件持久化

物件持久化 ifname main read scores pickle 將字典表序列化成字串pickle.dumps 字串變回字典用pickle.loads s import pickle person s pickle.dumps person 序列化 p pickle.loads s 恢復 序...