def loadpickle(fln):
"""
load a pickle and return content as dictionary
Parameters
==========
fln : string
filename
Returns
=======
out : dict
dictionary with content from file
See Also
========
savepickle
Examples
========
**note**: If fln is not found, but the same filename with '.gz'
is found, will attempt to open the .gz as a gzipped file.
>>> d = loadpickle('test.pbin')
"""
if not os.path.exists(fln) and os.path.exists(fln + '.gz'):
gzip = True
fln += '.gz'
else:
try:
with open(fln, 'rb') as fh:
try: #Py3k
return pickle.load(fh, encoding='latin1')
except TypeError:
return pickle.load(fh)
except pickle.UnpicklingError: #maybe it's a gzip?
gzip = True
else:
gzip = False
if gzip:
try:
import zlib
with open(fln, 'rb') as fh:
stream = zlib.decompress(fh.read(), 16 + zlib.MAX_WBITS)
try: #Py3k
return pickle.loads(stream, encoding='latin1')
except TypeError:
return pickle.loads(stream)
except MemoryError:
import gzip
with open(fln) as fh:
gzh = gzip.GzipFile(fileobj=fh)
try: #Py3k
contents = pickle.load(gzh, encoding='latin1')
except TypeError:
contents = pickle.load(gzh)
gzh.close()
return contents
# -----------------------------------------------
评论列表
文章目录