Python configparser 模块
【摘要】 如果想用python生成一个这样的文档怎么做呢?
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
创建文件
来看一个好多软件的常见文档格式如下:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
如果想用python生成一个这样的文档怎么做呢?
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11': 'yes' } config['bitbucket.org'] = {'User': 'hg'} config['topsecret.server.com'] = {'Host Port': '50022', 'ForwardX11': 'no'} with open("config.ini", "w", encoding="utf-8") as configfile: config.write(configfile) configfile.close()
结果:
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
查找文件
import configparser config = configparser.ConfigParser() # ---------------------------查找文件内容,基于字典的形式 print(config.sections()) config.read("config.ini") print(config.sections()) print("bytebong.com" in config) print("bitbucket.org" in config) print(config["bitbucket.org"]["user"]) print(config["DEFAULT"]["Compression"]) print(config["topsecret.server.com"]["Forwardx11"]) print(config["bitbucket.org"]) for key in config: # 注意,有default会默认default的键 print(key) print(config.options("bitbucket.org")) # 同for循环,找到'bitbucket.org'下所有键 print(config.items("bitbucket.org")) # 找到'bitbucket.org'下所有键值对 print(config.get("bitbucket.org", 'compression')) # get方法Section下的key对应的value
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/YuchuanDemo010.py [] ['bitbucket.org', 'topsecret.server.com'] False True hg yes no <Section: bitbucket.org> DEFAULT bitbucket.org topsecret.server.com ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11'] [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')] yes Process finished with exit code 0
增删改操作
import configparser config = configparser.ConfigParser() config.read("config.ini") config.add_section("yuchuan") config.remove_section("bitbucket.org") config.remove_option("topsecret.server.com", "forwardx11") config.set("topsecret.server.com", "k2", "22222") config.set("yuchuan", "kk", "666666") config.write(open("new.ini", "w", encoding="utf-8"))
结果:
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [topsecret.server.com] host port = 50022 k2 = 22222 [yuchuan] kk = 666666
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)