繁体   English   中英

使用 ConfigParser Python 更改 ini 文件中的值

[英]Change value in ini file using ConfigParser Python

所以,我有这个 settings.ini :

[SETTINGS]

value = 1

这个python脚本

from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('settings.ini')

print parser.get('SETTINGS', 'value')

如您所见,我想读取然后将值“1”替换为另一个值。 到目前为止,我所能做的就是阅读它。 我在网上搜索如何更换它,但我没有找到。

从文档的例子来看:

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)

我有一个问题: with open

另一种方式:

import configparser

def set_value_in_property_file(file_path, section, key, value):
    config = configparser.RawConfigParser()
    config.read(file_path)
    config.set(section,key,value)                         
    cfgfile = open(file_path,'w')
    config.write(cfgfile, space_around_delimiters=False)  # use flag in case case you need to avoid white space.
    cfgfile.close()

可用于修改java属性文件: file.properties

下面的示例将有助于更改 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/

Pythonconfigparser的官方文档说明了如何读取、修改和编写配置文件。

import configparser

config = configparser.ConfigParser()
config.read('settings.ini')
config.set('SETTINGS', 'value','15')

with open('settings.ini', 'w') as configfile:
    config.write(configfile)

暂无
暂无

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

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