python 读写 ini 文件
.ini 文件是配置文件,一般存放配置信息
一个 .ini 文件由多个 section 组成,每个 section 下可以有多个键值对
结构如下:
1 2 3 4 5 6
| [user] # 这里是 section username = admin # k = v 的形式保存 password = passwd # 一个 section 下可以允许多个键值对
[info] # 可以存在多个 section nickname = test
|
导包
python 下读取 ini 文件需要 configparser 模块
1
| pip install configparser
|
写入
1 2 3 4 5 6 7 8 9 10 11
| import configparser
config = configparser.ConfigParser()
config.add_section('header')
config.set('header', 'Referer', 'xxxx')
config.write(open('config.ini','a'))
|
config.ini
读取(展示方法获取的数据为 str 类型,注意数据转换)
1 2 3 4 5 6 7 8 9 10 11
|
config.read('config.ini')
value = config.get('header', 'Referer') print(value)
print(type(value))
value = config['header']['Referer']
|