28 -1 configparserp 配置模块

这个模块不太重要。。。 因为现在都用框架了

我们的配置文件有两个去处

  1、py文件

    需要import ,用模块的方式以变量的形式取值

  2、其他文件

    f = open('文件')     以字符串取值

还有一种介于1、2之间  

configparserp :

  • 有一种固定格式的配置文件
  • 有一个对应的模块去帮你做这个文件的字符串处理

我们把配置项存在setting.ini 配置文件

  格式如下

[path]   # 分组  section
userinfo_path = D:sylarpython_workspaceday26userinfo    #配置项   option
studentinfo_path = D:sylarpython_workspaceday26userinfo  # option

   我们如何用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)

生成了example.ini

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

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no
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  判断bytebong.com在不在config里面
print('bitbucket.org' in config)  # True    判断bitbucket.org在不在config里面
print(config['bitbucket.org']["user"])  # hg  取值
print(config['DEFAULT']['Compression'])  # 可以拿到值yes
print(config['topsecret.server.com']['ForwardX11'])  # 可以拿到值no
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方法Section下的key对应的value

增删改查:

import configparser

config = configparser.ConfigParser()

config.read('example.ini')

config.add_section('yuan')



config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com',"forwardx11")


config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')

config.write(open('new2.ini', "w"))
原文地址:https://www.cnblogs.com/zhuangdd/p/12663237.html