Python3 配置文件(configparser)
本文由 Luzhuo 编写,转发请保留该信息.
原文: http://blog.youkuaiyun.com/rozol/article/details/72793304
以下代码以Python3.6.1为例
Less is more!
configparser 可以读写和解析注释文件, 但是没有写入注释的功能
#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/26'
# config_configparser.py 配置文件
# configparser 可以读写和解析注释文件, 但是没有写入注释的功能
import configparser
import re
config_str = '''
# 配置文件信息案例
[DEFAULT]
minSdkVersion = 15
targetSdkVersion = 24
versionName = 1.0.0
server action = yes
[luzhuo.me]
user = luzhuo
# This is a comments.
[mysql]
ip = 127.0.0.1
port = 3306
'''
def config_write():
'''
生成配置文件, 字典的形式添加数据
'''
config = configparser.ConfigParser()
config['DEFAULT'] = {
'minSdkVersion': '15',
'targetSdkVersion': '24',
'versionName': '1.0.0',
'server action': 'yes'}
config['luzhuo.me'] = {}
config['luzhuo.me']['user'] = 'luzhuo'
config['mysql'] = {}
topsecret = config['mysql']
topsecret['ip'] = '127.0.0.1'
topsecret['port'] = '3306'
with open('config.ini', 'w') as configfile:
config.write(configfile)
def conf