您的位置:首页 > 编程语言 > Python开发

python学习之路-7 模块configparser/xml/shutil/subprocess以及面向对象初级入门

2016-06-23 08:16 791 查看

本篇记录内容

模块

configparser

xml

shutil

subprocess

面向对象

面向对象基础

面向对象编程和函数式编程对比

面向对象中对象和类的关系

面向对象之构造方法

面向对象之应用场景实例

面向对象之对象中封装对象

面向对象之单继承

面向对象之多继承

模块

1、configparser 配置文件解析,可以解析固定格式的配置文件,例如mysql的配置文件,下面通过一些例子详细介绍configparser的一些功能

配置文件text.txt的内容如下

[section1]
k1 = 111
k2 : 222
[section2]
k = 4dd
k1 = k2


通过模块configparser处理上面格式的配置文件

import configparser     # 导入configparser模块

config = configparser.ConfigParser()   # 实例化一个对象

config.read("test.txt", encoding="utf-8")  # 读取配置文件内容

获取所有节点名称
ret = config.sections()
print(ret)
# 输出
['section1', 'section2']

获取指定节点下所有的键值对
ret = config.items('section1')
print(ret)
# 输出
[('k1', '111'), ('k2', '222')]

获取指定节点下所有的键
ret = config.options("section1")
print(ret)
# 输出
['k1', 'k2']

获取指定节点下指定的key的值
ret = config.get("section1", "k1")
print(ret)
# 输出
111

检查节点名称"section1"是否存在,返回 True, False
ret = config.has_section("section1")
print(ret)
# 输出
True

检查节点名称"section1"中是否含有键"k1", 返回True或False
ret = config.has_option("section1", "k1")
print(ret)
# 输出
True

添加一个名称为"section100"的节点
config.add_section("section100")
config.write(open("test.txt", "w"))
# 输出
没有输出,会在文件中新增一个section100的节点

删除名称为"section100"的节点
config.remove_section("section100")
config.write(open("test.txt", "w"))
# 输出
没有输出,会在文件中删除名称为section100的节点

在已经存在节点名称"section2"中添加一个键值对 k1 = k2, 如果该节点名称不存在,则会报错
ret = config.set("section2", "k1", "k2")
config.write(open("test.txt", "w"))
# 输出
没有输出,会在文件中节点名称为"section2"下面添加一个键值对  k1 = k2

2、XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:

<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2026</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>

解析xml的两种方式

将字符串解析成xml对象

from xml.etree import ElementTree

# 从文件中读取含有XML格式的内容,将内容保存到一个变量中
str_xml = open('test.xml', "r").read()

# 将str_xml字符串实例化成一个对象root,root为该字符串的根节点
root = ElementTree.XML(str_xml)
print(root)
print(root.tag)  # 根节点的名称

# 输出
<Element 'data' at 0x101ac79a8>
data


将文件解析成xml对象

# 直接解析含有xml类型数据的文件
tree = ElementTree.parse("test.xml")

# 实例化成对象, root为根节点
root = tree.getroot()
print(root)
print(root.tag)

# 输出
<Element 'data' at 0x1011c79a8>
data
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: