使用configparser模块读取配置文件
读取.ini文件
abc.ini
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [com.net] user = knight [ip,yeyese.clu] port = 1010 forwardx11 = no
读取操作
from configparser import ConfigParser cfgg = ConfigParser() s = cfgg.read('abc.ini') print(s) # 读取配置文件的每个节段 m = cfgg.sections() print(m) # 返回字符串 p = cfgg.get('com.net','User') print(p) # 返回boolean 值 n = cfgg.getboolean('DEFAULT','Compression') print(n) # 返回整型 port = cfgg.getint('ip,yeyese.clu','Port') print(port)
修改
from configparser import ConfigParser cfg = ConfigParser() cfg.read('abc.ini') cfg.set('ip,yeyese.clu','Port','1010') with open('abc.ini','w') as f: cfg.write(f)
添加
from configparser import ConfigParser cfg = ConfigParser() cfg.read('abc.ini') cfg.add_section('user') cfg.set('user','lzj','123') cfg.set('user','hu','123') cfg.set('user','xing','123') cfg.set('user','zhuo','123') with open('abc.ini','w') as f: cfg.write(f)
创建配置文件
from configparser import ConfigParser cfg = ConfigParser() cfg.read('ab.ini') cfg.add_section('user') cfg.set('user','lzj','123') cfg.set('user','hu','123') cfg.set('user','xing','123') cfg.set('user','zhuo','123') with open('ab.ini','w') as f: cfg.write(f)
删除节段
from configparser import ConfigParser cfg = ConfigParser() cfg.read('abc.ini') cfg.remove_section('user') with open('abc.ini','w') as f: cfg.write(f)
使用pyyaml 模块读取yml文件
import yaml import os # 获取当前脚本所在文件夹路径 curPath = os.path.dirname(os.path.realpath(__file__)) print(curPath) # 获取yaml文件夹路径 yamlPath = os.path.join(curPath,'nb.yaml') from pathlib import Path mypath = Path(yamlPath) print(mypath) if not mypath.exists(): # windows创建文件命令 os.popen("type nul>{}".format(yamlPath)) import time time.sleep(1) print(yamlPath) f = open(yamlPath,'r',encoding='utf8') d = yaml.load(f,Loader=yaml.FullLoader) # ** # Loader 如果不加这个参数,会出现警告 print(d) print(d['nb']['user']) print(d['redis']) print(d['redis']['host']) f.close()
菜鸟的自白
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现