脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python内置模块ConfigParser实现配置读写功能的方法

Python内置模块ConfigParser实现配置读写功能的方法

2021-01-15 00:33苍松 Python

这篇文章主要介绍了Python内置模块ConfigParser实现配置读写功能的方法,涉及Python使用ConfigParser模块进行配置读、写、修改、删除等操作的相关实现技巧,需要的朋友可以参考下

本文实例讲述了Python内置模块ConfigParser实现配置读写功能的方法。分享给大家供大家参考,具体如下:

用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。

?
1
2
3
4
5
6
7
#配置文件test.cfg
[section1]
k1 = v1
k2 :v2
k3 = 1
[section2]
k1 = v1
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('test.cfg')
# ########## 读 ##########
#获取所有sections.
secs = config.sections()
print secs #['section1', 'section2']
#获取制定section的键key
options = config.options('section1')
print options  #['k1', 'k2', 'k3']
#获取指定section的键值对key-value
item_list = config.items('section1')
print item_list #[('k1', 'v1'), ('k2', 'v2'), ('k3', '1')]
#获取指定key的value
# 获取字符串类型的value
val1 = config.get('section1','k1')
# 获取整型的value
val2 = config.getint('section1','k3')
# ########## 增改删 ##########
# 增加section
if not config.has_section('section3'):
  config.add_section('section3')
  config.write(open('test.cfg', "w"))
#设置option
if not config.has_section('section3'):
  config.set('section3','k1',11111)
  config.write(open('test.cfg', "w"))
# 移除option
ret = config.remove_option('section3','k1')
print ret  #True or False
config.write(open('test.cfg', "w"))
# 移除section
ret = config.remove_section('section3')
print ret  #True or False
config.write(open('test.cfg', "w"))

希望本文所述对大家Python程序设计有所帮助。

原文链接:http://www.cnblogs.com/tkqasn/p/6027214.html

延伸 · 阅读

精彩推荐