获取Python从字典输出.py文件?

时间:2014-06-27 09:30:14

标签: python pickle

如何让Python输出并保存从字典生成的.py文件?

例如,我想动态生成此文件:

file.py

import time

PROJECT_NAME = "YOUR_PROJECT_NAME"
USER = "TEST USER"

来自以下字典:

{'PROJECT_NAME': 'YOUR_PROJECT_NAME', 'USER': 'TEST'}

这就是我的尝试:

 with open('file.py', 'wb') as handle:
            pickle.dump(values, handle)

但这给了:

(dp0
S'PROJECT_NAME'
p1
S'USER'
p2

1 个答案:

答案 0 :(得分:0)

试试这个

with open('file.py', 'wb') as handle:
    handle.write("{")
    for k,v in your_dict.iteritems():
        handle.write("'%s' : '%s'," % (k,v))
    handle.write("}\n")