python第九期学习笔记(十)(模块)

本文摘自:
https://www.cnblogs.com/jin-xin/articles/9265561.html

configparser模块:
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)
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 configfile:
config.write(configfile)

该代码会生成如下图中的配置文件:

 访模块的增删除改查操作如下案例,超级简单:

 

 删除操作:

import configparser
config=configparser.ConfigParser()
config.read('example.ini')
config.remove_option('topsecret.server.com','forwardx11')
#删除section选项会连下面的option都删除
config.remove_section('bitbucket.org')


 
 ElementTree格式化输出:

#!/usr/bin/python3
#_*_ coding:utf-8 _*_
#Time:2019/10/23 17:04
import xml.etree.ElementTree as ET

#ElementTree模块不带缩进功能,可以使用如下函数,设置缩进
def indent(elem, level=0):
i = " " + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i

new_xml=ET.Element('People')
name=ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age=ET.SubElement(new_xml,"age",attrib={'checked':'no'})
sex=ET.SubElement(new_xml,"sex")
sex.text='male'
age.text='33'
name.text='tom'
et=ET.ElementTree(new_xml)
indent(new_xml)
et.write('test.xml',encoding='utf-8',xml_declaration=True)
ET.dump(new_xml)

 

 

 

 

原文地址:https://www.cnblogs.com/gaoyuxia/p/11725497.html