end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

データの永続化(serialize)において pickle for python ≒ Storable for perl

そんな気がします

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import pickle


def main():
    test_vals = {"hoge":"hoge_val","foo":2}
    print test_vals

    # バイナリ書込みmodeでopen
    # 他modeには以下があり.
    # r:読み, w:書き, a:追記, +:読書き両方   t:text(default),b:binary
    # またwith構文により、close()不要にしています
    with open('sample.pickle', mode='wb') as f:
        pickle.dump(test_vals, f, protocol=2) #fileへの書込み(保存)

    restored_vals = {}
    with open('sample.pickle', mode='rb') as f:
        restored_vals = pickle.load(f)        #fileからの読込み

    print restored_vals


if __name__ == '__main__':
    main()

↑こう書くと↓こう表示されます

$ python test_pickle.py 
{'foo': 2, 'hoge': 'hoge_val'}
{'foo': 2, 'hoge': 'hoge_val'}

pythonでのfile open/closeやwithの勉強にもなりました