Python中configparser模块的使用方法

发布时间:2020-07-17 15:55:45 作者:小猪
来源:亿速云 阅读:128

这篇文章主要讲解了Python中configparser模块的使用方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

1、生成配置文件

''' 
  生成配置文件
'''
import configparser

config = configparser.ConfigParser()

# 初始化赋值
config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9'}
# 追加
config['DEFAULT']['ForwardX11'] = 'yes'

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'   # mutates the parser
topsecret['ForwardX11'] = 'no' # same here

with open('example.ini', 'w') as configfile:
  config.write(configfile)

2、读取配置文件

# 读
import configparser
config = configparser.ConfigParser()
config.sections()
config.read('example.ini')
# {'serveraliveinterval': '45', 'compression': 'yes', 'compressionlevel': '9', 'forwardx11': 'yes'}
print(config.defaults())

# hg
print(config['bitbucket.org']["User"])

# 50022
print(config["topsecret.server.com"]["host port"])

3、删除

# 删除(创建一个新文件,并删除 bitbucket.org)
import configparser
config = configparser.ConfigParser()
config.sections()

config.read('example.ini')
rec = config.remove_section("bitbucket.org") # 删除该项
config.write(open("example.cfg","w"))

生成新文件 example.cfg

DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

topsecret.server.com]
host port = 50022
forwardx11 = no

删除,并覆盖原文件

# 删除(删除 bitbucket.org)
import configparser
config = configparser.ConfigParser()
config.sections()

config.read('example.ini')
rec = config.remove_section("bitbucket.org") # 删除该项
config.write(open("example.ini","w"))

4、修改

import configparser

config = configparser.ConfigParser()

config.read('example.ini') #读文件

config.add_section('yuan') #添加section

config.remove_section('bitbucket.org') #删除section
config.remove_option('topsecret.server.com',"forwardx11") #删除一个配置项

config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
with open('new2.ini','w') as f:
   config.write(f)

生成新文件 new2.ini

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[topsecret.server.com]
host port = 50022
k1 = 11111

[yuan]
k2 = 22222

看完上述内容,是不是对Python中configparser模块的使用方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Python configparser模块 与 subprocess 模块
  2. configparser模块

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python configparser

上一篇:如何架设尽量安全的混合云网络

下一篇:Vue中Cli浏览器兼容性实践的详细解析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》