python物件持久化

2021-10-02 23:50:08 字數 1888 閱讀 6056

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)print

(type

(p))

shelve模組

import shelve

scores =[99

,100,88

]student =

db = shelve.

open

('shelve_student'

)#宣告建立乙個資料庫

db['s'

]= student #將字典表student序列化到資料庫檔案裡,並且賦予鍵值's'

db['scores'

]= scores

len(db)

#檢查資料庫中有幾個物件,用len()檢視鍵值

2temp_student = db[

's']

temp

traceback (most recent call last)

: file ""

, line 1,in

nameerror: name 'temp'

isnot defined

temp_student

type

(temp_student)

<

class

'dict'

>

temp_scores[99

,100,88

]type

(temp_scores)

<

class

'list'

>

shelve序列化自定義類例項

import  shelve

class

student

:def

__init__

(self,name,age)

: self.name = name

self.age = age

def__str__

(self)

:return self.name

defwirte_shelve()

: s = student(

'tom',25

) db = shelve.

open

('shelve_student_db'

) db[

's']

= s db.close(

)def

read_shelve()

: db = shelve.

open

('shelve_student_db'

) st = db[

's']

print

(st)

print

(st.name)

print

(st.age)

db.close(

)if __name__ ==

'__main__'

: read_shelve(

)

python 物件持久化

print open persondb.dat rb read testdemo2.py 讀取資料庫 載入乙個例項的時候,類極其模組的檔案都必須匯入 該類的例項再次載入的時候,對類的源 檔案的修改會自動選取 import testdemo import shelve db shelve.open p...

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 恢復 序...