如何实现Python中ini配置文件读写操作
发表于:2026-11-02 作者:千家信息网编辑
千家信息网最后更新 2026年11月02日,这篇文章将为大家详细讲解有关如何实现Python中ini配置文件读写操作,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。导入模块import configparser
千家信息网最后更新 2026年11月02日如何实现Python中ini配置文件读写操作
这篇文章将为大家详细讲解有关如何实现Python中ini配置文件读写操作,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
导入模块
import configparser # py3
写入
config = configparser.ConfigParser()config["DEFAULT"] = { 'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9' }config['bitbucket.org'] = {}config['bitbucket.org']['User'] = 'hg'config['topsecret.server.com'] = {}topsecret = config['topsecret.server.com']topsecret['Host Port'] = '50022' # mutates the parsertopsecret['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes'# 写入文件with open('example.ini', 'w') as configfile: config.write(configfile)读取
config = configparser.ConfigParser()config.read("example.ini")print(config.defaults())# OrderedDict([('compression', 'yes')])print(config.sections())# ['bitbucket.org', 'topsecret.server.com']print(config['bitbucket.org']['User'])# hgprint(config.options("topsecret.server.com"))# ['port', 'compression']print(config.items("topsecret.server.com"))# [('compression', 'yes'), ('port', '50022')]print(config.get("topsecret.server.com", "port"))# 50022修改
print(config.has_section("Name"))# 删除config.remove_section("Name")# 添加config.add_section("Name")config["Name"]["name"] = "Tom"config["Name"]["asname"] = "Jimi"# 设置config.remove_option("Name", "asname")config.set("Name", "name", "Jack")# 保存config.write(open("example.ini", "w"))附:ini文件
[DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = 9forwardx11 = yes[bitbucket.org]user = hg[topsecret.server.com]host port = 50022forwardx11 = no
help(configparser)
"""CLASSES class ConfigParser(RawConfigParser) | ConfigParser implementing interpolation. | | add_section(self, section) | Create a new section in the configuration. Extends | RawConfigParser.add_section by validating if the section name is | a string. | | set(self, section, option, value=None) | Set an option. Extends RawConfigParser.set by validating type and | interpolation syntax on the value. | | defaults(self) | | get(self, section, option, *, raw=False, vars=None, fallback=
关于"如何实现Python中ini配置文件读写操作"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
文件
篇文章
配置
更多
不错
实用
内容
文章
模块
知识
D.
F.
参考
帮助
有关
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
互联网科技行业发展
互联网科技有限公司经营范围
互联网和科技创新
互联网品科技
港股互联网科技股
互联网科技的发展
猫创互联网科技
长亮科技互联网金融
互联网科技公司需要的职位
互联网教育科技公司vipkid
创业天下互联网科技有限公司
互联网科技寓意
乌鲁木齐新华智原互联网科技学校
内蒙古九一互联网科技
广东工业互联网大赛深圳学泰科技
产业互联网科技服务公司
珠海东科互联网科技有限公司
互联网领先科技活动
山东蛋芒互联网科技有限公司
北京瑞云互联网科技有限公司
盈实互联网科技
重庆互联网络科技
兼蜜互联网科技
互联网前沿科技
中国科技互联网公司收入
民营互联网公司国防科技
翼展科技 首家互联网医院
互联网科技接地气
艺电能源互联网科技有限公司招聘
上海万顺科技互联网有限公司招聘