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

二十二、configparser

时间:2017-11-29 23:37:53      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:一个   循环   实例   文件内容   bitbucket   with open   server   方法   查找文件   

configparser

  用于读写文件,但是必须是下面的格式

  将这种文件当字典处理:

      {key:{key1=value}}

[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‘,
                     ‘ForwardX11‘:‘yes‘
                     }
config[‘bitbucket.org‘] = {‘User‘:‘hg‘}
config[‘topsecret.server.com‘] = {‘Host Port‘:‘50022‘,‘ForwardX11‘:‘no‘}
with open(‘example.ini‘, ‘w‘) as f:
   config.write(f)

  

import configparser

config = configparser.ConfigParser()
#---------------------------查找文件内容,基于字典的形式
print(config.sections())        #  []
config.read(‘example.ini‘)
print(config.sections())    #   [‘bitbucket.org‘, ‘topsecret.server.com‘] 查字段的名字;这里没有DEFAULT,是默认的,它的信息是共有的,最好别轻易改动,其他的是自定义的

print(‘bytebong.com‘ in config) # False     判断字段是否存在
print(‘bitbucket.org‘ in config) # True     。。。。

print(config[‘bitbucket.org‘]["user"])  # hg    字典方式取值
print(config[‘DEFAULT‘][‘Compression‘]) #yes    。。。
print(config[‘topsecret.server.com‘][‘ForwardX11‘])  #no   。。。

print(config.items("bitbucket.org"))    # [(‘serveraliveinterval‘, ‘45‘), (‘compression‘, ‘yes‘), (‘compressionlevel‘, ‘9‘), (‘forwardx11‘, ‘yes‘), (‘user‘, ‘hg‘)]
print(config[‘bitbucket.org‘])          #<Section: bitbucket.org>

for key in config[‘bitbucket.org‘]:     # 注意,有default会默认default的键
    print(key)
print(config.options(‘bitbucket.org‘))  # 同for循环,找到‘bitbucket.org‘下所有键
print(config.items(‘bitbucket.org‘))    #找到‘bitbucket.org‘下所有键值对
print(config.get(‘bitbucket.org‘,‘compression‘)) # yes       get方法取深层嵌套的值

  

增删改

import configparser

config = configparser.ConfigParser()
config.read(‘example.ini‘)
config.add_section(‘shuai‘)
config.remove_section(‘bitbucket.org‘)
config.remove_option(‘topsecret.server.com‘,"forwardx11")
config.set(‘topsecret.server.com‘,‘k1‘,‘11111‘)
config.set(‘shuai‘,‘k‘,‘666‘)
config.write(open(‘new2.ini‘, "w"))

  

二十二、configparser

标签:一个   循环   实例   文件内容   bitbucket   with open   server   方法   查找文件   

原文地址:http://www.cnblogs.com/Mr-chenshuai/p/7923081.html

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