有没有一种Python方法可以重写settings.py
等文件中的字典值?
有时,制作带有某些设置的*.py
文件是很有用的。在我的settings.py
中,有一个与keys
及其values
共同的dictionary
。例如下载停止的位置。在这种情况下,我想重写这个dictionary
,以便能够从这个步骤继续。
设置.py:
settings = {'driver':'firefox',
'last_processed_file':'x1.txt'}
如果我想将"x1.txt"重写为另一个文件/字符串,该怎么办?当然,我可以使用一些不舒服的解析或将字典保存为对象来实现这一点,但两者都有缺点。
因此,如果我想更改"last_processed_file"的值,我会执行类似settings.change_value("last_processed_file','x2.txt")的操作,结果将重写文件settings.py
:
设置.py:
settings = {'driver':'firefox',
'last_processed_file':'x2.txt'}
可能很傻,但你不能直接将字典的字符串表示转储回settings.py
(如果你只有"简单"的原因值):
settings = {'driver':'firefox',
'last_processed_file':'x1.txt'}
def dump(fpath, **kwargs):
with open(fpath, 'w') as outfile:
for key, value in kwargs.iteritems():
outfile.write('{0} = {1}n'.format(key, repr(value)))
dump('/tmp/settings.cfg', settings=settings)