11Python标准库系列之configparser模块

简介:

Python标准库系列之configparser模块


This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.


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

配置文件格式如下:

1
2
3
4
5
6
# 第一种注释方式
; 第二种注释方式
 
[node1]   # 节点
k1  =  v1   # key = value
k2 : v2   # key : value

实例

创建一个file.conf文件,内容为空,然后进入pythonIDE:

1
2
3
4
5
6
[root@ansheng ~] # touch file.conf 
[root@ansheng ~] # python
Python  2.6 . 6  (r266: 84292 , Jul  23  2016 15 : 22 : 56
[GCC  4.4 . 7  20120313  (Red Hat  4.4 . 7 - 11 )] on linux2
Type  "help" "copyright" "credits"  or  "license"  for  more information.
>>>

为文件添加节点

1
2
3
4
5
6
7
8
>>>  import  configparser
>>> config  =  configparser.ConfigParser()
>>> config.read( 'file.conf' , encoding = 'utf-8' )
[ 'file.conf' ]
# 添加节点"node1","node2",然后写入文件
>>> config.add_section( "node1" )
>>> config.add_section( "node2" )
>>> config.write( open ( 'file.conf' 'w' ))

检查节点是否存在

1
2
3
4
5
6
7
# 如果文件存在则返回"True",否则就返回"False"
>>>  print (config.has_section( 'node1' ))
True
>>>  print (config.has_section( 'node2' ))
True
>>>  print (config.has_section( 'node3' ))
False

删除节点

1
2
3
4
5
6
# 如果删除的节点存在则返回"True",否则返回"False"
>>> config.remove_section( "node2" )
True
>>> config.write( open ( 'file.conf' 'w' ))
>>>  print (config.has_section( 'node2' ))
False

设置节点内的键值对

1
2
3
4
5
6
# 添加完键值对之后别忘记了写入到文件中
>>> config. set ( 'node1' 'Name' "ansheng" )
>>> config. set ( 'node1' 'Blog_URL' "https://blog.ansheng.me" )
>>> config. set ( 'node1' 'Hostname' "localhost.localhost" )
>>> config. set ( 'node1' 'IP' "127.0.0.1" )
>>> config.write( open ( 'file.conf' 'w' ))

检查节点内的key是否存在

1
2
3
4
5
6
7
# 如果节点的Key存在就返回"True",否则返回"False"
>>>  print (config.has_option( 'node1' 'Name' ))
True
>>>  print (config.has_option( 'node1' 'IP' ))
True
>>>  print (config.has_option( 'node1' 'VV' ))
False

删除节点内的key

1
2
3
4
5
6
# 如果删除的节点存在就返回"True",否则就返回"False"
>>> config.remove_option( 'node1' 'IP' )
True
>>> config.write( open ( 'file.conf' 'w' ))
>>>  print (config.has_option( 'node1' 'IP' ))
False

获取指定节点下指定key的值

1
2
3
4
5
6
7
8
9
# 默认返回的是字符串类型
>>> config.get( 'node1' 'Name' )
'ansheng'
>>> config.get( 'node1' 'Blog_URL' )
'https://blog.ansheng.me'
# 返回的字符串我们可以设置成一下三种数据类型,分别是"int","float","bool"
# v = config.getint('node1', 'k1')
# v = config.getfloat('node1', 'k1')
# v = config.getboolean('node1', 'k1')

获取指定节点下所有的key

1
2
3
# 返回节点下面所有的Key列表
>>> config.options( 'node1' )
[ 'name' 'blog_url' 'hostname' ]

获取指定节点下所有的键值对

# 返回一个列表,列表中每个元组就是一个键值对
>>> config.items('node1')
[('name', 'ansheng'), ('blog_url', 'https://blog.ansheng.me'), ('hostname', 'localhost.localhost')]

获取所有节点

1
2
3
# 获取当前文件中有多少个节点
>>> config.sections()
[ 'node1' ]









本文转自 Edenwy  51CTO博客,原文链接:http://blog.51cto.com/edeny/1925757,如需转载请自行联系原作者
目录
相关文章
|
5天前
|
Python
在Python中绘制K线图,可以使用matplotlib和mplfinance库
使用Python的matplotlib和mplfinance库可绘制金融K线图。mplfinance提供便利的绘图功能,示例代码显示如何加载CSV数据(含开盘、最高、最低、收盘价及成交量),并用`mpf.plot()`绘制K线图,设置类型为'candle',显示移动平均线(mav)和成交量信息。可通过调整参数自定义图表样式,详情参考mplfinance文档。
15 2
|
6天前
|
机器学习/深度学习 边缘计算 TensorFlow
【Python机器学习专栏】Python机器学习工具与库的未来展望
【4月更文挑战第30天】本文探讨了Python在机器学习中的关键角色,重点介绍了Scikit-learn、TensorFlow和PyTorch等流行库。随着技术进步,未来Python机器学习工具将聚焦自动化、智能化、可解释性和可信赖性,并促进跨领域创新,结合云端与边缘计算,为各领域应用带来更高效、可靠的解决方案。
|
6天前
|
Serverless Python
使用Python的pandas和matplotlib库绘制移动平均线(MA)示例
使用Python的pandas和matplotlib库绘制移动平均线(MA)示例:加载CSV数据,计算5日、10日和20日MA,然后在K线图上绘制。通过`rolling()`计算平均值,`plot()`函数展示图表,`legend()`添加图例。可利用matplotlib参数自定义样式。查阅matplotlib文档以获取更多定制选项。
17 1
|
6天前
|
数据采集 SQL 数据挖掘
Python数据分析中的Pandas库应用指南
在数据科学和分析领域,Python语言已经成为了一种非常流行的工具。本文将介绍Python中的Pandas库,该库提供了强大的数据结构和数据分析工具,使得数据处理变得更加简单高效。通过详细的示例和应用指南,读者将了解到如何使用Pandas库进行数据加载、清洗、转换和分析,从而提升数据处理的效率和准确性。
|
6天前
|
SQL 关系型数据库 MySQL
使用Python的pymysql库连接MySQL,执行CRUD操作
使用Python的pymysql库连接MySQL,执行CRUD操作:安装pymysql,然后连接(host='localhost',user='root',password='yourpassword',database='yourdatabase'),创建游标。查询数据示例:`SELECT * FROM yourtable`;插入数据:`INSERT INTO yourtable...`;更新数据:`UPDATE yourtable SET...`;删除数据:`DELETE FROM yourtable WHERE...`。
15 0
|
6天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{"name": "John", "age": 30, "city": "New York"}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
12 1
|
7天前
|
机器学习/深度学习 算法 数据挖掘
机器学习--K近邻算法,以及python中通过Scikit-learn库实现K近邻算法API使用技巧
机器学习--K近邻算法,以及python中通过Scikit-learn库实现K近邻算法API使用技巧
|
7天前
|
存储 Python Windows
轻松学会openpyxl库,Python处理Excel有如神助
轻松学会openpyxl库,Python处理Excel有如神助
|
7天前
|
NoSQL Python
在Python中,我们可以使用许多库来处理Excel文件
Python处理Excel常用pandas和openpyxl库。pandas的`read_excel`用于读取文件,`to_excel`写入;示例展示了数据框操作。openpyxl则用于处理复杂情况,如多工作表,`load_workbook`加载文件,`iter_rows`读取数据,`Workbook`创建新文件,写入单元格数据后保存。
14 1
|
7天前
|
Python
使用Seaborn库创建图形的使用案例
【4月更文挑战第29天】该代码段首先导入seaborn和matplotlib库,然后加载名为"titanic"的数据集。接着,它创建一个画布并设定子图大小。通过seaborn的FacetGrid以"Attrition_Flag"为列进行分组,映射数据到网格上,用histplot展示"Customer_Age"的直方图分布。同样,也使用boxplot方法生成"Freq"的箱线图。最后展示所有图形。
8 2