python之configparse模块
编写一个.ini配置文件
新建一个config对象,给section赋值一个字典,最后写入文件。
import configparser
config=configparser.ConfigParser()
config["DEFAULT"]={
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'PORT' : '3306',
'NAME':'request',
'USER':'root',
'PASSWORD': '123456',
'OPTIONS': {
'init_command':"SET sql_mode='STRICT_TRANS_TABLES'"
}
}
config['django_setting']={
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
with open("data.ini","w") as fp:
config.write(fp)

读取配置文件
新建一个config对象,读取配置文件,采用get方法或者字典读取section下的option的值
import configparser
config=configparser.ConfigParser()
config.read("data.ini")
keys=[]
print (config["django_setting"]) #<Section: django_setting>
print (config.get('DEFAULT','HOST')) #127.0.0.1
print (config['DEFAULT']['HOST']) #127.0.0.1
for key in config["django_setting"]:
keys.append(key)
print (keys) #['engine', 'name', 'host', 'port', 'user', 'password', 'options']
print (config.items("DEFAULT")) #[('engine', 'django.db.backends.mysql'), ('host', '127.0.0.1'), ('port', '3306'), ('name', 'request'), ('user', 'root'), ('password', '123456'), ('options', '{\'init_command\': "SET sql_mode=\'STRICT_TRANS_TABLES\'"}')]
改变配置文件
新建一个config对象,读取配置文件,add_section新增section,remove_section删除section,remove_option移出某个section中的键值对,set新增或者改变某个section中的某个option的值,最后写入配置文件
import configparser
config=configparser.ConfigParser()
config.read("data.ini")
config.add_section("new")
config.remove_section("django_setting")
config.remove_option("DEFAULT","ENGINE")
config.set("new","ad","123")
with open("data1.ini","w") as fp:
config.write(fp)


浙公网安备 33010602011771号