我喜欢在一个较长的python程序之后将我的数据存储为新脚本中的字典。这样,我就可以轻松地导入程序(以及数据),以便进行进一步的操作。
我写了这样的东西(一个旧的例子):
file = open(p['results']+'asa_contacts.py','w')
print>>file, \
'''
\'''
This file stores the contact residues according to changes in ASA
as a dictionary
\'''
d = {}
'''接下来是以字符串形式输入字典代码的大量麻烦:
print>>file, 'd[\'%s\'] = {}' %st我想知道是否有一个模块可以自动完成这一点,因为它会节省我很多时间。
谢谢
编辑:知道这些字典通常有几层深,就像我今天使用的字典一样,这可能会很有用:
d[ratio][bound][charge] = a_list发布于 2011-08-08 05:15:47
我不确定这是否是你想要的,但是尝试一下内置的函数repr。
repr(a)发布于 2011-08-08 05:13:26
除非您有需要源代码的特定原因--我怀疑没有,您只是想序列化和反序列化磁盘中的数据--更好的选择是Python的pickle module。
发布于 2011-08-08 10:20:40
repr的Lossy's suggestion恰好可以工作,但是repr不是专门为序列化设计的。我认为使用专门为此目的设计的工具会稍微更健壮一些;而且既然您想要的是人类可读的和-editable的东西,那么json是显而易见的选择。
>>> import json
>>> animals = {'a':'aardwolf', 'b':'beluga', 'c':'civet', 'd':'dik-dik',
'e':'echidna', 'f':'fennec', 'g':'goa', 'h':'hyrax',
'i':'impala', 'j':'javelina', 'k':'kudu', 'l':'lemur',
'm':'macaque', 'n':'nutria', 'o':'orca', 'p':'peccary',
'q':'quagga', 'r':'reebok', 's':'serval', 't':'tenrec',
'u':'urial', 'v':'vole', 'w':'wallaroo', 'x':'xenurine',
'y':'yapok', 'z':'zoologist'}
>>> s = json.dumps(animals)
>>> s[:60] + '...'
'{"a": "aardwolf", "c": "civet", "b": "beluga", "e": "echidna...'
>>> animals = json.loads(s)
>>> animals['w']
u'wallaroo'https://stackoverflow.com/questions/6975808
复制相似问题