常用模块——configparser模块

configparser模块

用于解析配置文件的模块
何为配置文件
包含配置程序信息的文件就称为配置文件
什么样的数据应作为配置信息
需要改 但是不经常改的信息 例如数据文件的路径 DB_PATH

配置文件中 只有两种内容

种是section 分区
一种是option 选项 就是一个key=value形式
我们用的最多的就是get功能 用来从配置文件获取一个配置选项

读取cfg文件的步骤
#创建一个解析器
config = configparser.ConfigParser()
# 读取并解析test.cfg
config.read('test.cfg',encoding='utf-8')
#获得分区
print(config.sections())
#获得’path'分区下选项
print(config.options('path'))
#['path', 'user']
#['dp_file']
#获取某分区的某选项的值
print(config.get("path","dp_file"))
print(type(config.get("user","age")))
# # get返回的都是字符串类型  如果需要转换类型 直接使用get+对应的类型(bool int float)
print(type(config.getint("user","age")))
print(type(config.get("user","age")))

不常用

# 是否由某个选项
config.has_option()
# 是否由某个分区
config.has_section()
# 添加
config.add_section("server")
config.set("server","url","192.168.1.2")
# 删除
config.remove_option("user","age")
# 修改
config.set("server","url","192.168.1.2")
# 写回文件中
with open("test.cfg", "wt", encoding="utf-8") as f:
    config.write(f)

猜你喜欢

转载自www.cnblogs.com/msj513/p/9806465.html