51
>>> shell
①
2
>>> entry
②
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'entry' is not defined
>>> import pickle
>>> with open('entry.pickle', 'rb') as f:
③
...
entry = pickle.load(f)
④
...
>>> entry
⑤
{'comments_link': None,
'internal_id': b'\xDE\xD5\xB4\xF8',
'title': 'Dive into history, 2009 edition',
'tags': ('diveintopython', 'docbook', 'html'),
'article_link':
'http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition',
'published_date': time.struct_time(tm_year=2009, tm_mon=3, tm_mday=27, tm_hour=22, tm_min=20, tm_sec=42, tm_wday=4, tm_yday=86, tm_isdst=-1),
'published': True}
1. ThisisPythonShell#2.
2. Thereisno
entry
variabledefined here.Youdefined an
entry
variableinPythonShell#1,butthat’sa
completelydifferentenvironmentwithitsownstate.
3. Openthe
entry.pickle
fileyou created inPythonShell#1.The
pickle
moduleusesabinarydataformat,so
youshould alwaysopenpicklefilesinbinary mode.
4. The
pickle.load()
functiontakesa
streamobject,readstheserializeddatafromthestream,createsanew
Pythonobject,recreatestheserializeddatainthenewPythonobject,and returns thenewPythonobject.
5. Nowthe
entry
variableisadictionarywithfamiliar-lookingkeys and values.
The
pickle.dump() / pickle.load()
cycleresultsinanewdatastructurethatisequaltotheoriginaldata
structure.
314