python中confIgparser模块学习
python中configparser模块学习
1 | ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键 = 值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。 |
目录
1 | 三种创建方法增删改查 |
三种创建方法
程序示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import configparser #实例化出来一个类,相当于生成一个空字典 config = configparser.ConfigParser() #创建也很简单,键:值 # 值:键---值 #第一种方法 config[ 'default' ] = { 'IP' : '192.168.14.2' , 'PORT' : '6072' } #第二种方法 config[ 'Custom' ] = {} config[ 'Custom' ][ 'User' ] = 'admin' config[ 'Custom' ][ 'Password' ] = '123456' <br> #第三种方法 config[ 'define' ] = {} Config = config[ 'define' ] Config[ 'Host' ] = '192.168.14.2' Config[ 'Port' ] = '611' with open ( 'confile' , 'w' ) as configfile: #注意这里,是谁调用write方法,是config对象,不是文件对象 config.write(configfile) |
运行结果:
1 2 3 4 5 6 7 8 9 10 11 | [default] ip = 192.168 . 14.2 port = 6072 [Custom] user = admin password = 123456 [define] host = 192.168 . 14.2 port = 611 |
增删改查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import configparser config = configparser.ConfigParser() #读取配置文件 config.read( 'confile' ) print ( '获取文件内所有的section:' ) print (config.sections()) print ( '获得指定section下所有option:' ) options = config.options( 'Custom' ) print (options) print ( '---------------------------查' ) print ( '获取指定option下的值:' ) value1 = config[ 'Custom' ][ 'user' ] print (value1) value2 = config.get( 'Custom' , 'user' ) print (value2) # getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。 print ( '获取指定section下所有的键值对:' ) items = config.items( 'default' ) print (items) print ( '遍历键值对:' ) for key in config[ 'default' ]: print (key)<br> #下面都会改变文件,所以最后一步都要重新写入配置文件 print ( '---------------------------增' ) print ( '添加section:' ) # config.add_section('key1') print ( '添加键值对:' ) # config.set('key1','k1','123456') print ( '---------------------------改' ) #如果需要修改配置文件里面的值,自行打开修改<br> print ( '---------------------------删' ) print ( '删除section:' ) config.remove_section( 'key1' ) print ( '删除键值对:' ) config.remove_option( 'key1' , 'k1' ) #重新保存 config.write( open ( 'confile' , 'w' )) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?