python之日常开发常用库
1. 配置文件解析(configobj)
pip install configobj
基本使用:
配置文件
[server]name = zbj
port = 9000
[home]
# 注释
area = huizhou
示例:
from configobj import ConfigObj# 实例化一个Configobj对象,给ConfigObj一个配置文件的路径,然后通过字典来访问成员,子段也是一个字典
cfg_path = "./test.cfg"
config = ConfigObj(cfg_path, encoding=\'UTF-8\')
# 读配置文件
print(config[\'server\']) # {\'name\': \'zbj\', \'port\': \'9000\'}
print(config[\'server\'][\'name\']) # zbj
#修改配置
from configobj import ConfigObjcfg_path = "./test.cfg"
config = ConfigObj(cfg_path, encoding=\'UTF-8\')
config[\'server\'][\'name\'] = "clj"
# 修改完记得write写入配置文件
config.write()
# 添加新项
from configobj import ConfigObj
cfg_path = "./test.cfg"
config = ConfigObj(cfg_path, encoding=\'UTF-8\')
config[\'school\'] = {}
config[\'school\'][\'class\'] = "three"
# 只要进行了修改(包括新增删除等)的操作,记得write修改
config.write()
# 删除配置项
from configobj import ConfigObjcfg_path = "./test.cfg"
config = ConfigObj(cfg_path, encoding=\'UTF-8\')
del config[\'school\']
del config[\'server\'][\'port\']
config.write()
# 将配置文件内容写入不同文件
from configobj import ConfigObjcfg_path = "./test.cfg"
config = ConfigObj(cfg_path, encoding=\'UTF-8\')
config.filename = "./test.ini"
config.write()
# 此时会新建一个test.ini文件,然后会将test.cfg的内容写入到test.ini文件
# 创建新的配置文件
from configobj import ConfigObj# 实例化一个ConfigObj对象
config = ConfigObj()
# filename指定新创建的文件路径和名称
config.filename = \'./my_cfg.ini\'
# 写入配置信息
config[\'people\'] = {}
config[\'people\'][\'name\'] = \'zzbj\'
config[\'people\'][\'age\'] = \'18\'
config.write()
以上是 python之日常开发常用库 的全部内容, 来源链接: utcz.com/z/386477.html