码迷,mamicode.com
首页 > 其他好文 > 详细

day6 ConfigParser模块 yaml模块

时间:2017-05-29 21:43:54      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:实现   lin   section   plain   com   code   number   写法   ring   

    yaml模块:

    python可以处理yaml文件,yaml文件安装的方法为:$ pip3 install pyyaml


   configparser模块,用来处理文件的模块,可以实现文件的增删改查

    configparser用于处理特定格式的文件,其本质上是利用open来操作文件

    下面来看看configarser模块的功能:  

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

[bitbucket.org]
user = hg

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

    上面代码格式就是configparser的常见格式,这中文件格式在有些地方很常见。

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,生成一个空字典
topsecret["Host Port"] = "50022"            #给字典添加键值对
topsecret["Forwardx11"] = "no"
config["DEFAULT"]["Forwardx11"] = "yes"
with open("config_file.ini","w") as configfile:
    config.write(configfile)

运行如下:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

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

    从上面代码可以看出,其文件的格式类似于字典的形式,包含keys和values类型,我们首先要定义一个configparser的文件,然后往文件中添加键值对。如上面代码所示:

    上面我们把字典写进文件之后,如何读取呢?下面来看看configparser.ConfigParser的文件操作:

    读取:

    >>> import configparser
  >>> config = configparser.ConfigParser()           #定义一个文件信息
  >>> config.sections()
  []

  >>> config.read(‘example.ini‘)
  [‘example.ini‘]
   
    >>> config.sections()
    [‘bitbucket.org‘, ‘topsecret.server.com‘]
    下面来看看configparser模块中文件的增删改查:
import configparser

config = configparser.ConfigParser()
config.read("config_file.ini")

#删除文件中的字段
sec = config.remove_section("bitbucket.org")
config.write(open("config_file.ini","w"))

#添加新的字段到文件中
# sec = config.has_section("alex")
# config.add_section("alex")
# config["alex"]["age"] = "21"
# config.write(open("config_file.ini","w"))


#修改字段中的文件信息
config.set("alex","age","28")
config.write(open("config_file.ini","w"))

    上面代码的字段中,我们实现了增删改查的功能。要了解文件中的功能即可。并且能够操作,其实很多时候都对文件操作的思路都是相同的,只是实现的方式不一样,代码的写法不一样而已。

day6 ConfigParser模块 yaml模块

标签:实现   lin   section   plain   com   code   number   写法   ring   

原文地址:http://www.cnblogs.com/gengcx/p/6919043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!