此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
常用方法:
import configparser
conf = configparser.ConfigParser() # 先生成一个对象.
conf.read("conf.ini") # 读取配置文件
print(conf.sections()) # 输出配置文件里的配置项,注意,获取不到default.因为每个配置文件里都有一个default.所以这里给省略略
list = list(conf["bitbucket.org"].keys()) #其实conf["bitbucket.org"] 就是一个字典.可以取里面的值.可是为什么还有default里的值? print(list)
['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11'] print(conf["bitbucket.org"]["user"]) # 获取"user"key的value
a = conf["bitbucket.org"]["user"]
print(a) # hg
conf["bitbucket.org"]["user"] = "jack" # 修改user的值
b = conf["bitbucket.org"].get("user")
print(b) #jack # 我们获取一下conf["bitbucket.org"]的key
for k in conf["bitbucket.org"]:
print(k) '''user
serveraliveinterval
compression
compressionlevel
forwardx11 ''' # 输出了好多key,但是conf["bitucket.org]里只有一个key啊.default的作用就是默认每个节点里都会有default的配置. if "ssss" in conf["bitbucket.org"]: # 判断一个子项是否在conf["bitbucket.org"]里面
print("in") else:
print("not in") print(conf.options("group1")) # 获取group1下面的key,也就是子项的名字 # 添加新项
conf.add_section("group3")
conf["group3"]["user"] = "Nick"
conf["group3"]["age"] = "" # 注意,写入数字的时候必须用引号引起来,不然会认为是一个int类型,无法写入.
conf.write(open("conf_test.ini", "w")) #删除
conf.remove_option("group1","k1") # 删除子项下的值
conf.write(open("1111.ini", "w")) conf.remove_section("group1") # 删除一个子项
conf.write(open("2222.ini", "w"))
作业:
[DEFAULT] [client]
port = 3306
socket = /data/mysql_3306/mysql.sock [mysqld]
explicit_defaults_for_timestamp = true
port = 3306
socket = /data/mysql_3306/mysql.sock
back_log = 80
basedir = /usr/local/mysql
tmpdir = /tmp
datadir = /data/mysql_3306
default-time-zone = '+8:00' """
1.修改时区 default-time-zone = '+8:00' 为 校准的全球时间 +00:00
2.删除 explicit_defaults_for_timestamp = true
3.为DEFAULT增加一条 character-set-server = utf8 """
import configparser
conf = configparser.ConfigParser() #生成一个conf对象
conf.read("conf.ini") # 读取conf.ini的内容
conf.remove_option("mysqld", "explicit_defaults_for_timestamp") # 删除
#修改
conf["mysqld]["default-time-zone"] = "+00:00" # 增加
conf["DEFAULT"]["character-set-server"] = "utf8"
作业答案
补充:
for k,v in (conf["mysqld"].items()): # 取所有的k,v
print(k,":", v) """输出:
port : 3306
socket : /data/mysql_3306/mysql.sock
back_log : 80
basedir : /usr/local/mysql
tmpdir : /tmp
datadir : /data/mysql_3306
default-time-zone : +00:00
character-set-server : utf8 """