configparser模块
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)
1.这个模块可以帮您写以下这种文件
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
实现方法如下:
# 创建一个这种文件 import configparser confi = configparser.ConfigParser() # []括号里的是节,{}里面是你在这个节里要创建的参数 confi["DEFAULT"] ={"ServerAliveInterval":"45", "Compression":"yes", "CompressionLevel":"9", "ForwardX11":"yes"} confi["bitbucket.org"]={"User":"hg"} confi["topsecret.server.com"]={"Port":'50022',"ForwardX11":'no'} # 打开或创建一个文件进行写入 with open("expet.conf",'w') as fig: confi.write(fig)
2.增删改查
import configparser fig = configparser.ConfigParser() fig.read('expet.conf') fig.add_section("size") # 添加一个节 fig.remove_section("size") # 删除一个节 fig.remove_option("topsecret.server.com",'forwardx11') # 删除某个节里的一个配置参数 fig.set("topsecret.server.com",'port','66666') # 修改某个节里面的一个配置参数 with open('expet.conf','w') as f: # 进行写入 fig.write(f)