configparser 模块
# import configparser # #创建一个配置文件 # config = configparser.ConfigParser() # config["DEFAULT"] = {"ServeAliveInterval":"45", # "Compression":"yes", # "CompressionLevel ":"9", # "ForwardXll":"yes" # } # config["bitbucket.org"] = {} # config["bitbucket.org"]["User"] = "hg" # # # config["topsecret.server.com"] = {} # to = config["topsecret.server.com"] # to["Port"] = "50022" # to["ForwardXll"] = "no" # # #config["DEFAULT"]["ForwardXll"] = "yes" # # # with open("example.ini","w")as configfile: # config.write(configfile) #---------------------------------------------增删改查 import configparser config = configparser.ConfigParser() config.read("example.ini") #-----------------------------------------查 ''' print(config.sections()) #获取文件 #config.read("example.ini") #获取ini文件内所有的section,以列表形式返回['bitbucket.org', 'topsecret.server.com'] print(config.sections()) #判断文件中的内容是否存在 print("bitbucket.org"in config) #查bitbucket.org对应的user的值是什么“hg” print(config["bitbucket.org"]["user"]) print(config["topsecret.server.com"]["port"]) print(config["DEFAULT"]) #DEFAULT的原因,如果要遍历它不要用DEFAULT命名 for key in config["bitbucket.org"]: print(key) #获取指定bitbucket.org下所有options ,以列表形式返回 # ['user', 'forwardxll', 'compression', 'servealiveinterval', 'compressionlevel] print(config.options("bitbucket.org")) #获取指定bitbucket.org下所有的键值对 #[('forwardxll', 'yes'), ('compression', 'yes'), ('servealiveinterval', '45'), ('compressionlevel', '9'), ('user', 'hg')] print(config.items("bitbucket.org")) #获取bitbucket.org中的值,返回为string类型 print(config.get("bitbucket.org","user")) ''' #--------------------------------------增删改 config.add_section("yuan") config.set("yuan","k1","gggg") #删除 config.remove_section("topsecret.server.com") config.remove_option("bitbucket.org","user") config.write(open("i.cfg","w"))
ConfigParser模块在python3中修改为configparser.这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同
该模块的作用 就是使用模块中的RawConfigParser()、ConfigParser()、 SafeConfigParser()这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查 操作。
1 read(filename) #读取配置文件,直接读取ini文件内容 2 3 sections() #获取ini文件内所有的section,以列表形式返回['logging', 'mysql'] 4 5 options(sections) #获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password'] 6 7 items(sections) #获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')] 8 9 get(section, option) #获取section中option的值,返回为string类型 10 >>>>>获取指定的section下的option <class 'str'> 127.0.0.1 11 12 getint(section,option) 返回int类型 13 getfloat(section, option) 返回float类型 14 getboolean(section,option) 返回boolen类型
https://www.cnblogs.com/lhly/p/8066898.html

浙公网安备 33010602011771号