随笔 - 139  文章 - 0 评论 - 0 阅读 - 33825
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

configparse模块

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

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

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

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

复制代码
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('example.ini', 'w') as f1:
    config.write(f1)
复制代码

2、查找文件

import configparser
config = configparser.ConfigParser()
config.read('example.ini')   

查找文件内容,基于字典的形式

print(config.sections())        #['bitbucket.org', 'topsecret.server.com']

通过原码可以看到read默认有2个参数:filenames, encoding=None,如果有中文就需要指定编码

config.read('example.ini', encoding='utf8')

判断key值是否在config中

print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True

打印'DEFAULT'下面的键

print(config['DEFAULT']) #<Section: DEFAULT>
print(config['DEFAULT']['compression'])  #yes

打印Section下的key

复制代码
for k in config['DEFAULT']:
    print(k)
# serveraliveinterval
# compression
# compressionlevel
# forwardx11

for k in config['bitbucket.org']:
    print(k + ':' + config['bitbucket.org'][k])
# user:hg
# serveraliveinterval:45
# compression:yes
# compressionlevel:9
# forwardx11:yes
# 注意,有default会默认输出default的键
复制代码

找出所有键值对

print(config.options('bitbucket.org'))
# ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
# 同for循环,找到'bitbucket.org'下所有键,有default会默认输出default的键

找到Section下所有键值对

print(config.items('DEFAULT'))
# [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')]

print(config.items('bitbucket.org'))
# # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

get方法Section下的key对应的value

print(config.get('DEFAULT', 'compression')) #yes
print(config.get('topsecret.server.com', 'host port')) #50022

3、增删改操作

import configparser

config = configparser.ConfigParser()
config.read('example.ini', encoding='utf8')

增加

config.add_section('test1')
with open('example.ini', 'w') as f:
config.write(f)
# 增加了一个section,名称为[test1]

删除

复制代码
config.remove_section('bitbucket.org')
with open('example.ini', 'w') as f:
config.write(f)
# 删除了section:[bitbucket.org]

config.remove_option('topsecret.server.com', 'forwardx11')
with open('example.ini', 'w') as f:
config.write(f)
# 删除了topsecret.server.com下的forwardx11键值对
复制代码

修改

复制代码
config.set('topsecret.server.com', 'k1', '123')
config.set('topsecret.server.com', 'host port', '50021')
config.set('test1', 'k2', '111')
config.write(open('example.ini', 'w')) #注意写完要保存!!!
# 设置topsecret.server.com下的k1的值为123, 设置host port的值为50021 # 设置test1下的k2的值为111 # set方法,有则更改,无则添加 # config.write(open(file, 'w'))写法同with open(file, 'w') as config_file:config.write(config_file) example.ini 结果: [DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [topsecret.server.com] host port = 50021 k1 = 123 [test1] k2 = 111
复制代码

 

posted on   longfei2021  阅读(101)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示