您现在的位置是:主页 > news > 东平做网站/全网整合营销
东平做网站/全网整合营销
admin2025/6/22 7:19:36【news】
简介东平做网站,全网整合营销,仿摄影网站,免费建网站域名configparser模块 用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。 来看一个好多软件的常见文档格式如下:haproxy.conf 内容如下: [DEFAULT] ServerAliveInterval 45 Compression yes CompressionLev…
东平做网站,全网整合营销,仿摄影网站,免费建网站域名configparser模块 用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。 来看一个好多软件的常见文档格式如下:haproxy.conf 内容如下:
[DEFAULT]
ServerAliveInterval 45
Compression yes
CompressionLev…
configparser模块 用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
来看一个好多软件的常见文档格式如下:haproxy.conf 内容如下:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes[bitbucket.org]
User = hg[topsecret.server.com]
Port = 50022
ForwardX11 = no
如何用python生成一个这样的文档呢?
导入模块
import configparser #在python2.x 是 ConfigParser
config = configparser.ConfigParser() #创建一个配置模块对象,赋值给config
config["DEFAULT"] = {'ServerAliveInterval': '45', #创建默认节点配置'Compression': 'yes','CompressionLevel': '9'}
config['abcd.org'] = {} #创建第二个节点配置。创建一个空字典
config['abcd.org']['User'] = 'hg' #给abcd.org节点添加信息
config['aaa.server.com'] = {} #创建第三个节点配置,创建一个空字典
topsecret = config['aaa.server.com'] #给aaa.org节点添加信息
topsecret['Host Port'] = '50022'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'with open('example.ini', 'w') as configfile: #将配置信息写入到example.ini文件config.write(configfile)
把刚刚创建的example.ini文件内容读出来
import configparser
config = configparser.ConfigParser()
print(config.sections()) #打印config对象的节点sections,因为还没有数据,所以打印出来是空的。
config.read("example.ini") #读取example.ini文件
print(config.sections()) #打印config对象的sections
print("abcd.org" in config) #判断abcd.org在不在config中,返回True或False
print(config["abcd.org"]["user"]) #打印config中abcd.org节点下的user信息
print(config["DEFAULT"]["compression"]) #打印config中default节点下compression信息
print(config["aaa.server.com"]["forwardx11"]) #打印config中aaa.server.com节点下forwardx11的信息
for key in config["DEFAULT"]: #遍历config中DEFAULT中的key
print(key)
print(config["DEFAULT"][key])
现增删改查
ha.conf文件内容:
[section1]
k1 = v1
k2:v2
k3 = 3[section2]
k1 = v1导入模块,创建configparser对象
import configparser
config = configparser.ConfigParser()
config.read("ha.conf")#读取
section = config.sections()
print(section)
print(config.items())#获取config中section1节点下的k1 的value
print(config.get("section1","k1"))#获取config中section1节点下的k3 的value ,value必须是int类型,否则报错
print(config.getint("section1","k3"))#判断config中的section1节点下k1 选项存在不存在,不存在返回False
print(config.has_option("section1","k1"))
print(config.has_option("section1","k4"))#删除、修改#删除config中的section
config.remove_section("section2")#修改config中的section1中的option的k1 值
config.set("section1","k1","111")#在config中增加节点section3
config.add_section("section3")#增加config中section3中option key:k1 value:111
config.set("section3","k1","111")#删除config中section1节点下的k2 option
config.remove_option("section1","k2")#将config内容重新写入新的文件i.cfg,也可以写回原来的文件ha.conf 原来的内容将会被覆盖。
config.write(open("i.cfg","w"))本文转自 506554897 51CTO博客,原文链接:http://blog.51cto.com/506554897/2046053