Python 之ConfigParser

本文介绍ConfigParser模块的基本使用方法,包括如何读取配置文件、获取配置信息、修改配置值等。并提供了一些示例代码来展示如何进行配置文件的管理和操作。
一、ConfigParser简介

ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。

1: [db] 2: db_host = 127.0.0.1 3: db_port = 22 4: db_user = root 5: db_pass = rootroot 6:  7: [concurrent] 8: thread = 10 9: processor = 20

中括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。

 

二、ConfigParser 初始工作

使用ConfigParser 首选需要初始化实例,并读取配置文件:

1: cf = ConfigParser.ConfigParser() 2: cf.read("配置文件名")

 

三、ConfigParser 常用方法

1. 获取所有sections。也就是将配置文件中所有“[ ]”读取到列表中:

1: s = cf.sections() 2: print 'section:', s

将输出(以下将均以简介中配置文件为例):

1: section: ['db', 'concurrent']

2. 获取指定section 的options。即将配置文件某个section 内key 读取到列表中:

1: o = cf.options("db") 2: print 'options:', o

将输出:

1: options: ['db_host', 'db_port', 'db_user', 'db_pass']

3. 获取指定section 的配置信息

1: v = cf.items("db") 2: print 'db:', v

将输出:

1: db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'rootroot')]

4. 按照类型读取指定section 的option 信息

同样的还有getfloat、getboolean。

1: #可以按照类型读取出来 2: db_host = cf.get("db", "db_host") 3: db_port = cf.getint("db", "db_port") 4: db_user = cf.get("db", "db_user") 5: db_pass = cf.get("db", "db_pass") 6:  7: # 返回的是整型的 8: threads = cf.getint("concurrent", "thread") 9: processors = cf.getint("concurrent", "processor") 10:  11: print "db_host:", db_host 12: print "db_port:", db_port 13: print "db_user:", db_user 14: print "db_pass:", db_pass 15: print "thread:", threads 16: print "processor:", processors

将输出:

1: db_host: 127.0.0.1 2: db_port: 22 3: db_user: root 4: db_pass: rootroot 5: thread: 10 6: processor: 20

5. 设置某个option 的值。(记得最后要写回)

1: cf.set("db", "db_pass", "zhaowei") 2: cf.write(open("test.conf", "w"))

6.添加一个section。(同样要写回)

1: cf.add_section('liuqing') 2: cf.set('liuqing', 'int', '15') 3: cf.set('liuqing', 'bool', 'true') 4: cf.set('liuqing', 'float', '3.1415') 5: cf.set('liuqing', 'baz', 'fun') 6: cf.set('liuqing', 'bar', 'Python') 7: cf.set('liuqing', 'foo', '%(bar)s is %(baz)s!') 8: cf.write(open("test.conf", "w"))

7. 移除section 或者option 。(只要进行了修改就要写回的哦)

1: cf.remove_option('liuqing','int') 2: cf.remove_section('liuqing') 3: cf.write(open("test.conf", "w"))

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. from ConfigParser import ConfigParser
  3. CONFIGFILE="f.txt"
  4. config=ConfigParser()
  5. config.read(CONFIGFILE)
  6. print config.get('messages','greeting')
  7. radius=input(config.get('messages','questions')+' ')
  8. print config.get('messages','result')
  9. print config.getfloat('numbers','pi')*radius**2

  10. s=config.sections()
  11. print'section: ',s
  12. o=config.options('messages')
  13. print'messages option: ',o
  14. v=config.items("messages")
  15. print'message de xinxi: ',v

  16. config.add_section('liuyang1')
  17. config.set('liuyang1','int','15')
  18. config.set('liuyang'1,'hhhh','hello world')
  19. config.write(open("f.txt","w"))
  20. print config.get('liuyang1','int')
  21. print config.get('liuyang1','hhhh')





  22. #!/usr/bin/env python
  23. import ConfigParser
  24. import sys
  25. config=ConfigParser.ConfigParser()
  26. config.add_section("book1")
  27. config.set("book1","title","hello world")
  28. config.set("book1","aut","log")
  29. config.write(open("f.txt","w"))

Python 中的 `configparser` 模块是标准库的一部分,用于处理配置文件。配置文件通常用于存储应用程序的配置信息,例如数据库连接参数、日志级别设置等。该模块支持读取、写入和修改配置文件,这些文件通常采用类似 INI 格式的结构。这种格式与 Windows 的 INI 文件格式相同,因此 `configparser` 可以轻松地与这些文件进行交互 [^1]。 ### 基本用法 #### 对象初始化 使用 `configparser` 时,首先需要创建一个 `ConfigParser` 对象: ```python import configparser config = configparser.ConfigParser() ``` #### 配置文件格式 一个典型的 INI 文件由多个节(section)组成,每个节包含多个键值对(option 和 value): ``` [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 [bitbucket.org] User = hg [topsecret.server.com] Port = 22 ForwardX11 = no ``` #### 读取配置文件 使用 `read()` 方法可以加载配置文件: ```python config.read('example.ini') ``` #### 获取所有的 sections 可以获取配置文件中的所有节: ```python sections = config.sections() ``` #### 获取指定 section 下的 option 值 使用 `get()` 方法可以获取指定节下的选项值: ```python server_alive_interval = config.get('DEFAULT', 'ServerAliveInterval') ``` #### 获取指定 section 的所有配置信息 可以使用 `items()` 方法来获取指定节的所有配置信息: ```python items = config.items('bitbucket.org') ``` #### 修改某个 option 的值 使用 `set()` 方法可以修改某个选项的值,并使用 `write()` 方法将更改写入文件: ```python config.set('DEFAULT', 'CompressionLevel', '10') with open('example.ini', 'w') as configfile: config.write(configfile) ``` #### 添加 section 和 option 使用 `add_section()` 方法可以添加新的节: ```python config.add_section('new_section') ``` #### 删除 section 和 option 使用 `remove_section()` 或 `remove_option()` 方法可以删除节或选项: ```python config.remove_section('topsecret.server.com') config.remove_option('DEFAULT', 'CompressionLevel') ``` #### 异常处理 在使用 `configparser` 模块时,可能会遇到一些异常,例如试图访问不存在的节或选项时会引发 `NoSectionError` 或 `NoOptionError`。 ### 常见用途 `configparser` 模块常用于应用程序中以管理配置数据,这使得配置信息易于维护并且可以避免硬编码配置信息。此外,它也支持将配置数据转换为字典形式以便进一步处理 [^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值