简体   繁体   English

Python将字典写入文件

[英]Python write dictionary to file

I have a original config file which I found a very nice way to read. 我有一个原始的配置文件,我发现了一种非常好的阅读方式。 Like this: 像这样:

myDict = {}
cfg = file(configFile, 'r').readlines()
myDict = eval('\n'.join(cfg))

This gets my file's contents in to myDict very nicely. 这将我文件的内容很好地存储到myDict中。 But what is a simple looking way to make changes to its contents and create/write to a new modified file? 但是,改变其内容并创建/写入新的修改文件的简单方法是什么? thanks 谢谢

You could try this (overlooking the security hole of eval): 您可以尝试一下(忽略eval的安全漏洞):

myDict = {}
with open(configFile, 'r+') as file:
    cfg = file.readlines()
    myDict = eval('\n'.join(dgf))
    myDict['new key'] = 'new value'

    file.seek(0)
    file.write(str(myDict)) #format this if you want, str() is raw
    file.truncate()

The above should open the file, evaluate the contents as a dict (as per your code), add a new value (just modifying the dictionary), and then overwrite the original file. 上面的代码应该打开文件,将内容作为dict(根据您的代码)进行评估,添加新值(只需修改字典),然后覆盖原始文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM