Python configparser 模块

网友投稿 527 2022-05-29

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

创建文件

来看一个好多软件的常见文档格式如下:

[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes    [bitbucket.org] User = hg    [topsecret.server.com] Port = 50022 ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

Python configparser 模块

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 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

软件开发 人工智能 机器学习 AI

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:《密码技术与物联网安全:mbedtls开发实战》 —1.2.2 物联网安全与密码学
下一篇:学习完 JavaScript后, 接下来该学习什么呢?
相关文章