【第五节】【Python学习】【configparser模块】

configparser模块

转载自https://www.cnblogs.com/plf-Jack/p/11170284.html

该模块适用于配置文件的格式与window ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

Configparse配置文件的格式

  [DEFAULT]

  passwd1=root123
  passwd2=Comm2011

  [filetype]
  type1=.py
  type2=.cpp

[bitbucket.org]
User = Atlan

生成上述配置文件

import configparser
config=configparser.ConfigParser()
config["DEFAULT"]={"passwd1":"root123", "passwd2":"Comm2011"}
config["filetype"]={"type1":".py", "type2":".cpp"}
config["bitbucket.org"]={"User":"Atlan"}
with open("example.ini","w") as configfile:
    config.write(configfile)
#config后面跟的是一个section的名字,section的段的内容的创建类似于创建字典。

读取文件内容

import configparser
config=configparser.ConfigParser()
print(config.sections())    #[]
config.read("example.ini")  #打开ini文件
print(config.sections())    #['filetype', 'bitbucket.org']
print("filetype" in config) #True
print(config["filetype"]["type1"])  #.py
print(config["filetype"])           #<Section: filetype>
#找到“filetype”下的所有键值对,
print(config.items("filetype")) #注意:有default会默认default的键值对,返回[('passwd1', 'root123'), ('passwd2', 'Comm2011'), ('type1', '.py'), ('type2', '.cpp')] for k, v in config.items("filetype"): print(k) print(v) keys=[] for key in config["filetype"]: #返回“filetype”下的所有键 keys.append(key) print(keys) #['type1', 'type2', 'passwd1', 'passwd2'] print(config.get("filetype","type2")) #get方法Section下的key对应的value

修改文件内容

config.read("example.ini")     
config.add_section("huangyu")  #添加section
config["huangyu"]={"a":"b"}    #为section添加配置项
config.remove_section("huangyu")   #删除section
config.remove_option("filetype","type1")   #删除一个配置项
config.set("filetype","type2",".html")     #修改一个配置项
with open("example1.ini","w") as f:        #另存为新的文件
    config.write(f)
原文地址:https://www.cnblogs.com/yuhuang/p/13558444.html