[python] 不錯的玩意, pickle與 shelve

最近在python裡頭做 xml 與 dictionary 的格式轉換,又需要讀/寫入 database,真的搞的我暈頭轉向又不好維護。
今天看到一本好書 core python programming  提到關於 file i/o, 原來python 有些 persistent storage modules就是專門處理這些問題,像是pickle與marshal。
主要是介紹pickle,
因為marshal的差別在於marshal僅支援簡單的types(number, sequence, mapping...)
這邊說錯了,marshal主要是處理序列化的對象(serialized object), 特別是python的 pseudo-compiled code, 即 .pyc. 而一般支援 persistence module in python 主要是指pickle跟shelve

至於什麼叫做 object serialization, 就是將複雜的物件轉為binary type或 text 物件的過程,為的是希望能夠透明性的儲存 python object 而不失去其身分或類型等訊息。


Pickle 可將python data type轉為bytes streams(使用dumps()),亦可從重新組回原data types(使用loads()),例如


>>> import pickle
>>> x = {'name':'glob', 'info':(27, 'single', 'student')}
>>> xp = pickle.dumps(x)
>>> y = pickle.loads(xp)
>>> y
{'info': (27, 'single', 'student'), 'name': 'glob'}


*亦可以用 dump(x, f)   f為file descriptor 寫入file中。

shelve 則是使用anydbm(一種DBM)來進行pickles的操作,算是結合db+pickles。


>>> import shelve
>>> sh = shelve.open('shelve.db')
>>> sh['myinfo'] = {'name':'glob', 'info':(27, 'single', 'student')}
>>> sh.close()


*註1:anydbm不支援multiple-write, 所以需要做flag, ex. shelve.open('shelve.db', flag='r')
*註2:anydbm在內容被更改時不支援自動修改,所以需要加write-back ex. shelve.open('shelve.db', writeback='True')

結論:感覺似乎找個強一點的database使用pickle存入會是最佳解  顆顆... 再評估

Comments

Popular posts from this blog

股票評價(Stock Valuation) - 股利折現模型

openwrt feed的使用

How to convert Markdown into HTML