【发布时间】:2014-07-18 08:59:00
【问题描述】:
如果我想将 Dictionary 结构保存到文件中,然后直接从文件中读取此 Dictionary,我有两种方法,但我不知道这两种方法之间的区别。谁能解释一下? 这是一个简单的例子。假设这是我的字典:
D = {'zzz':123,
'lzh':321,
'cyl':333}
第一种保存到文件的方法:
with open('tDF.txt','w') as f: # save
f.write(str(D) + '\n')
with open('tDf.txt','r') as f:
Data = f.read() # read. Data is string
Data = eval(Data) # convert to Dictionary structure format
第二种方法(使用pickle):
import pickle
with open('tDF.txt','w') as f: # save
pickle.dump(D,f)
with open('tDF.txt','r') as f:
D = pickle.load(f) # D is Dictionary structure format
我认为第一种方法很简单。有什么区别?
谢谢!
【问题讨论】:
标签: python file dictionary pickle