首页 > 编程语言 > 详细

python 配置文件 ConfigParser模块

时间:2019-05-16 17:00:22      阅读:110      评论:0      收藏:0      [点我收藏+]

ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

来看一个好多软件的常见文档格式如下

[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}
 
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
config[DEFAULT][ForwardX11] = yes
with open(example.ini, w) as configfile:
   config.write(configfile)

读取配置文件信息

#!/usr/bin/env python3
# -*- coding:utf-8 -*-


import configparser

config = configparser.ConfigParser()
config.sections()

config.read(example)

config.sections()

for i in config.keys():
    print(i, end= )
print("=" * 50)
print(config.keys())

print(config[bitbucket.org][User])

print(config[DEFAULT][Compression])

topsecret = config[topsecret.server.com]
print(topsecret[ForwardX11])
print(topsecret[Port])

for key in config[bitbucket.org]:
    print(key)

print(config[bitbucket.org][ForwardX11])

configparser增删改查语法

 

 
########### i.cfg file ##########
[section1]
k1 = v1
k2:v2
k5 : 10

[section2]
k3 = v3
k4 = v4
age : 88
 ################################# 
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: songwei

import configparser

# ########## 读 ##########

config = configparser.ConfigParser()
config.read(example)

secs = config.sections()
print(secs) #--->[‘section1‘, ‘section2‘]
options = config.options(section2)
print(options)  #--->[‘k3‘, ‘k4‘, ‘age‘]

item_list = config.items(section2)
print(item_list) #--->[(‘k3‘, ‘v3‘), (‘k4‘, ‘v4‘), , (‘age‘, ‘88‘)]

val = config.get("section1", "k2")
print(val) #--->v2 
val2 = config.getint(section1,k5)
print(val2)  #---> 10

# ########## 改写 ##########

config = configparser.ConfigParser()
config.read(example)
sec = config.remove_section(section1)  #删除
config.write(open(i.cfg, "w"))

sec = config.has_section(wupeiqi)
print(sec)
sec = config.add_section(wupeiqi)
print(sec)
config.write(open(i.cfg, "w"))


config.set(section2,k4,"11111")
#  config.defaults()
config.write(open(i.cfg, "w"))

# config.remove_option(‘section2‘,‘age‘)
# config.write(open(‘i.cfg‘, "w"))

 

python 配置文件 ConfigParser模块

原文:https://www.cnblogs.com/song-weiwei/p/10875950.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!