python修改配置文件,ini文件,configparser

文章目录


首先我们用到的包是 configparser,安装:

pip install configparser

有很多小伙伴都遇到一个问题,就是configparser其实对ini配置文件有要求的,有的ini文件里没有[default], [secation1]等以[***]这样的字眼,其实这是ini文件的头,所有如果没有的话会报错,如下错误:

MissingSectionHeaderError: File contains no section headers.

那么如果没有,可以自己添加,具体将ini文件怎么分类,看个人。我们有个params.ini的配置文件,内容如:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

这里一共有三个section,也就是三个中括号,所以这个ini被分为了三类,那么读取其中某个值就用一下命令来读取:

import configparser
config = configparser.ConfigParser()

读取params.ini文件,就会有如下输出:

In [6]: config.read('params.ini')
Out[6]: ['params.ini']

如果我们想要读取某一行的值,修改某一行的值,增加某一行,删除某一行的值:

##########################################################
# 输出某个参数的值:
In [8]: config['DEFAULT']['ServerAliveInterval']
Out[8]: '45'
In [10]: config['bitbucket.org']['User']
Out[10]: 'hg'
In [12]: config['topsecret.server.com']['Port']
Out[12]: '50022'
##########################################################
# 修改某个参数的值:
In [13]: config['DEFAULT']['ServerAliveInterval'] = '46'
In [14]: config['topsecret.server.com']['Port'] = 'jf'
In [15]: config['bitbucket.org']['User'] = '20000'
# 修改后的值:
In [17]: config['DEFAULT']['ServerAliveInterval']
Out[17]: '46'
In [18]: config['topsecret.server.com']['Port']
Out[18]: 'jf'
In [19]: config['bitbucket.org']['User']
Out[19]: '20000'
##########################################################
# 增加某个section:
In [20]: config.add_section('Section2')
# 然后在这个section下增加一个参数和值:
In [21]: config.set('Section2', 'newKey1', 'newValue1')
# 当然也可以在原来的section里增加一个值:
In [22]: config.set('DEFAULT', 'newKey2', 'newValue2')
##########################################################
# 删除某一行:
In [30]: config.remove_section('Section2')
Out[30]: True
In [34]: config.remove_option('DEFAULT','newKey2')
Out[34]: True
##########################################################
# 现在其实params.ini里的内容并没有改变,修改只是在缓存里,如果不保存就会丢失,而保存的话不能config.write('params.ini','w'),只能用循环保存
with open('params.ini', 'w') as configfile:
	config.write(configfile)
##########################################################

你可能感兴趣的:(python修改配置文件,ini文件,configparser)