使用 ConfigParser Python 更改 ini 文件中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27964134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change value in ini file using ConfigParser Python
提问by Prixeler
So, I have this settings.ini :
所以,我有这个 settings.ini :
[SETTINGS]
value = 1
And this python script
还有这个python脚本
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('settings.ini')
print parser.get('SETTINGS', 'value')
As you can see, I want to read and then replace the value "1" by another one. All I was able to do so far is to read it. I searched on the net how to replace it but I didn't find.
如您所见,我想读取然后将值“1”替换为另一个值。到目前为止,我所能做的就是阅读它。我在网上搜索如何更换它,但我没有找到。
采纳答案by Zah
As from the examples of the documentation:
从文档的例子来看:
https://docs.python.org/2/library/configparser.html
https://docs.python.org/2/library/configparser.html
parser.set('SETTINGS', 'value', '15')
# Writing our configuration file to 'example.ini'
with open('example.ini', 'wb') as configfile:
parser.write(configfile)
回答by Sampat Kumar
Below example will help change the value in the ini file:
下面的示例将有助于更改 ini 文件中的值:
PROJECT_HOME="/test/"
parser = ConfigParser()
parser.read("{}/conf/cdc_config.ini".format(PROJECT_HOME))
parser.set("default","project_home",str(PROJECT_HOME))
with open('{}/conf/cdc_config.ini'.format(PROJECT_HOME), 'w') as configfile:
parser.write(configfile)
[default]
project_home = /Mypath/

