Last active
August 29, 2015 14:03
-
-
Save yubessy/0cabb1f348a7a251d1ca to your computer and use it in GitHub Desktop.
Pythonのオブジェクト圧縮・展開
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# stdlib | |
import cPickle as pickle | |
import zlib | |
PROTOCOL = pickle.HIGHEST_PROTOCOL | |
def save_to_str(obj): | |
u""" | |
引数のオブジェクトを文字列にpickle化しzlibで圧縮したものを返す | |
"""Ï | |
result = zlib.compress(pickle.dumps(obj, PROTOCOL)) | |
return result | |
def load_from_str(s): | |
u""" | |
save_to_strによって圧縮された文字列を読み込んで元のオブジェクトを返す | |
""" | |
result = pickle.loads(zlib.decompress(s)) | |
return result | |
def save_to_file(obj, fname): | |
u""" | |
引数のオブジェクトをpickle化→zlib圧縮しファイルfnameに保存する | |
save_to_strを利用する | |
""" | |
s = save_to_str(obj) | |
with open(fname, 'w') as f: | |
f.write(s) | |
def load_from_file(fname): | |
u""" | |
save_to_fileによって圧縮されたファイルを読み込んで | |
元のオブジェクトを返す | |
load_from_strを利用する | |
""" | |
with open(fname) as f: | |
s = f.read() | |
result = load_from_str(s) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment