打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
ini配置文件操作方法

一、ini文件介绍

ini配置文件常用于存储项目全局变量

如:接口地址、输出文件路径、项目地址、用户名、密码等

二、ini文件编写格式

[节点]

选项=选项值

;表示注释

注意:节点名不可以重复【所以写入新节点前要判断是否存在】

三、.ini 文件读取

1、.ini文件读

import configparser

config = configparser.ConfigParser()
config.read('config.ini')
# 获取所有节点
sec = config.sections()
print(sec)
# 获取单个节点下所有选项
db = config.options(section="database")
print(db)
# 获取单个节点下某个选项值
username = config.get(section="database", option="username")
print(username)
# 获取某个节点下所有选项及选项值
value = config.items(section="database")
print(f"获取到的值是:{value}")

2、ini文件写

# 增加一个节点
config.add_section("db")
# 给节点增加选项和值
config.set(section="db", option="usr", value="chuanzhang")
# 保存操作
with open(os.path.dirname(__file__)+'/config.ini', mode='w+') as file:
config.write(file)
file.close()

3、删除

# 删除节点下某个选项
config.remove_option(section="db", option="pwd")
with open(os.path.dirname(__file__)+'/config.ini', mode='w+') as opt:
config.write(opt)
opt.close()
# 删除节点
config.remove_section("db")
# 删除后保存
with open(os.path.dirname(__file__)+'/config.ini', mode='w+') as data:
config.write(data)
data.close()
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python配置文件模块埋个坑,险些影响了版本上线!
[编程基础] Python配置文件读取库ConfigParser总结
python读写ini格式的配置文件
Python常用配置文件ini、json、yaml读写总结
Python 解析 ini 配置文件
如何使用Python3读取配置文件(ini)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服