python_day7模块configparserXMLrequestsshutil系统命令-面向对象之篇
Posted lcj122
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python_day7模块configparserXMLrequestsshutil系统命令-面向对象之篇相关的知识,希望对你有一定的参考价值。
python内置模块补充
一、configparser
configparser:用户处理特定格式的文件,其本质是利用open打开文件
# 节点
[section1]
#键值对k1 = v1 k2:v2
k1 = v1
#建:k1 k2
k2:v2
[section2]
k1 = v1
k3:v3
[section3]
k3 = v3
k4:v4
[section4]
k4 = v4
k5:v5
在configparser默认将获取的元素当做一个字符串进行处理,不用特定执行元素的类型
1、获取所有节点的元素:ret = config.sections()
import configparser
#configparser将里面的元素都当做一个字符串进行处理
# 获取节点路径
#创建
config = configparser.ConfigParser()
#将jiedian文件路径加载至config
config.read(\'jiedian\', encoding=\'utf-8\')
#获取所有【section】节点,此时注意获取所有的节点是复数形式
ret = config.sections()
print(ret)
#[\'section1\', \'section2\']
2、获取指定节点下的所有键值对:ret = config.items(\'section1\')
import configparser
# 获取指定节点下所有的键值对
config = configparser.ConfigParser()
config.read(\'jiedian\',encoding=\'utf-8\')
ret = config.items(\'section1\')
print(ret)
#[(\'k1\', \'v1\'), (\'k2\', \'V2\')]
3、获取指定节点下所有的建 :ret2= config.options(\'section2\')
import configparser
#获取节点下所有的建 config =configparser.ConfigParser() config.read(\'lcj.txt\',encoding= \'utf-8\')#读取lcj.txt文件,并按照utd-8读取文件 ret1 = config.options(\'section1\') ret2= config.options(\'section2\') print(ret1) print(ret2) ##[\'k1\', \'k2\'] # [\'k1\', \'k3\']
4、获取指定节点下指定Key的值:ret1 = config.get(\'section1\',\'k1\') ##get:获取节点中的key值
import configparser
#获取节点下指定Key的值
config =configparser.ConfigParser()
config.read(\'lcj.txt\',encoding= \'utf-8\') ##读取lcj.txt文件,并按照utd-8读取文件
ret1 = config.get(\'section1\',\'k1\') ##get:获取节点中的key值
print(ret1) #v1
ret2 = config.getint(\'section2\',\'k1\')
print(ret2) #231 #文件k1 = 231
ret3 = config.getfloat(\'section3\',\'k3\') #获取文件中的浮点数
print(ret3) #0.123 #文件:k3 = 0.123
ret4 = config.getboolean(\'section4\',\'k4\') #获取文件中的bool数据
print(ret4) #True #文件k4 = True
5、检查、删除、添加节点
检查:ww = config.has_section(\'section1\')
删除:config.remove_section(\'xiaoluo01\')
添加:config.add_section(\'xiaoluo01\')
import configparser
config =configparser.ConfigParser()
config.read(\'lcj.txt\',encoding= \'utf-8\') ##读取lcj.txt文件,并按照utd-8读取文件
#检查节点
# ww = config.has_section(\'section1\')
# print(ww) #如文件中存在,则返回一个bool类型:True,否则返回一个:False
#添加节点
config.add_section(\'xiaoluo01\')
# config.add_section(\'beijing\')
config.write(open(\'lcj.txt\',\'w\'))
# [beijing]
# [xiaoluo01]
#删除节点
config.remove_section(\'xiaoluo01\')
config.write(open(\'lcj.txt\',\'w\'))
6、检查、删除、设置指定组内的键值对
#检查建值对
has_opt = config.has_section(\'section1\',\'k1\')
#设置section2中建值对
config.set(\'section2\',\'k01\',\'12\') #将section2中建值对修改为:k01 = 12
config.write(open(\'lcj.txt\',\'w\'))
config.remove_option(\'section2\',\'k1\')
config.write(open(\'lcj.txt\',\'w\'))
import configparser
config =configparser.ConfigParser()
config.read(\'lcj.txt\',encoding= \'utf-8\') ##读取lcj.txt文件,并按照utd-8读取文件
#检查建值对
has_opt = config.has_section(\'section1\',\'k1\')
print(has_opt)
#设置section2中建值对
config.set(\'section2\',\'k01\',\'12\') #将section2中建值对修改为:k01 = 12
config.write(open(\'lcj.txt\',\'w\'))
#k01 = 12 #源文件:k1 = v1
#删除建值对
config.remove_option(\'section2\',\'k1\')
config.write(open(\'lcj.txt\',\'w\'))
#[section2]
二、XML
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>
1、游览器返回的字符串形式含有:
A:html
B:Json
C:XML
页面上做展示(字符串类型一个XML格式数据)
配合文件(当做文件保存在本地,并内存数据是XML格式)
xml格式:开始<data> 、、、内容、、、 </data>结尾
每一个节点都是一个Element对象,节点可嵌套节点
2、解析XML
A:利用ElementTree.XML将字符串解析成XML对象
#导入模块
from xml.etree import ElementTree as ET
# #打开文件,并读取xmL内容
str_xml = open(\'lcj.xml\',\'r\').read()
# print(str_xml)
#将字符串解析成特殊对象,root代指xml文件根节点
root = ET.XML(str_xml)
B:利用ElementTree.parse将文件直接解析成xml对象
from xml.etree import ElementTree as ET
#直接解析xml文件,将文件写入内存
tree = ET.parse(\'lcj.xml\')#内部用open打开lcj.xml文件,并把打开的xml文件赋值给一个tree对象,可通过tree对象直接对xml进行取值
#获取xml文件的根节点
root = tree.getroot() #getroot:获取xml文件中的根节点
print(root)
print(root.tag) #tag:获取根节点的名字 data
#获取根节点对象: <Element \'data\' at 0x00000000006D0A98> 类型:Element,根节点:data
常用用法:
tag:获取当前节点名字
from xml.etree import ElementTree as ET
#直接解析xml文件
tree = ET.parse(\'lcj.xml\')#内部用open打开lcj.xml文件,并把打开的xml文件赋值给一个tree对象,可通过tree对象直接对xml进行取值
#获取xml文件的根节点
root = tree.getroot() #getroot:获取xml文件中的根节点
# print(root)
print(root.tag) #tag:获取根节点的名字 data
#获取根节点对象: <Element \'data\' at 0x00000000006D0A98> 类型:Element,根节点:data
attrib:获取当前节点的属性
from xml.etree import ElementTree as ET
#直接解析xml文件
tree = ET.parse(\'lcj.xml\')#内部用open打开lcj.xml文件,并把打开的xml文件赋值给一个tree对象,可通过tree对象直接对xml进行取值
#获取xml文件的根节点
root = tree.getroot() #getroot:获取xml文件中的根节点
print(root.attrib)
#{} 返回一个字典属性
操作XML常用格式:
XML格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:
class Element:
"""An XML element.
This class is the reference implementation of the Element interface.
An element\'s length is its number of subelements. That means if you
want to check if an element is truly empty, you should check BOTH
its length AND its text attribute.
The element tag, attribute names, and attribute values can be either
bytes or strings.
*tag* is the element name. *attrib* is an optional dictionary containing
element attributes. *extra* are additional element attributes given as
keyword arguments.
Example form:
<tag attrib>text<child/>...</tag>tail
"""
当前节点的标签名
tag = None
"""The element\'s name."""
当前节点的属性
attrib = None
"""Dictionary of the element\'s attributes."""
当前节点的内容
text = None
"""
Text before first subelement. This is either a string or the value None.
Note that if there is no text, this attribute may be either
None or the empty string, depending on the parser.
"""
tail = None
"""
Text after this element\'s end tag, but before the next sibling element\'s
start tag. This is either a string or the value None. Note that if there
was no text, this attribute may be either None or an empty string,
depending on the parser.
"""
def __init__(self, tag, attrib={}, **extra):
if not isinstance(attrib, dict):
raise TypeError("attrib must be dict, not %s" % (
attrib.__class__.__name__,))
attrib = attrib.copy()
attrib.update(extra)
self.tag = tag
self.attrib = attrib
self._children = []
def __repr__(self):
return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))
def makeelement(self, tag, attrib):
创建一个新节点
"""Create a new element with the same type.
*tag* is a string containing the element name.
*attrib* is a dictionary containing the element attributes.
Do not call this method, use the SubElement factory function instead.
"""
return self.__class__(tag, attrib)
def copy(self):
"""Return copy of current element.
This creates a shallow copy. Subelements will be shared with the
original tree.
"""
elem = self.makeelement(self.tag, self.attrib)
elem.text = self.text
elem.tail = self.tail
elem[:] = self
return elem
def __len__(self):
return len(self._children)
def __bool__(self):
warnings.warn(
"The behavior of this method will change in future versions. "
"Use specific \'len(elem)\' or \'elem is not None\' test instead.",
FutureWarning, stacklevel=2
)
return len(self._children) != 0 # emulate old behaviour, for now
def __getitem__(self, index):
return self._children[index]
def __setitem__(self, index, element):
# if isinstance(index, slice):
# for elt in element:
# assert iselement(elt)
# else:
# assert iselement(element)
self._children[index] = element
def __delitem__(self, index):
del self._children[index]
def append(self, subelement):
为当前节点追加一个子节点
"""Add *subelement* to the end of this element.
The new element will appear in document order after the last existing
subelement (or directly after the text, if it\'s the first subelement),
but before the end tag for this element.
"""
self._assert_is_element(subelement)
self._children.append(subelement)
def extend(self, elements):
为当前节点扩展 n 个子节点
"""Append subelements from a sequence.
*elements* is a sequence with zero or more elements.
"""
for element in elements:
self._assert_is_element(element)
self._children.extend(elements)
def insert(self, index, subelement):
在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
"""Insert *subelement* at position *index*."""
self._assert_is_element(subelement)
self._children.insert(index, subelement)
def _assert_is_element(self, e):
# Need to refer to the actual Python implementation, not the
# shadowing C implementation.
if not isinstance(e, _Element_Py):
raise TypeError(\'expected an Element, not %s\' % type(e).__name__)
def remove(self, subelement):
在当前节点在子节点中删除某个节点
"""Remove matching subelement.
Unlike the find methods, this method compares elements based on
identity, NOT ON tag value or contents. To remove subelements by
other means, the easiest way is to use a list comprehension to
select what elements to keep, and then use slice assignment to update
the parent element.
ValueError is raised if a matching element could not be found.
"""
# assert iselement(element)
self._children.remove(subelement)
def getchildren(self):
获取所有的子节点(废弃)
"""(Deprecated) Return all subelements.
Elements are returned in document order.
"""
warnings.warn(
"This method will be removed in future versions. "
"Use \'list(elem)\' or iteration over elem instead.",
DeprecationWarning, stacklevel=2
)
return self._children
def find(self, path, namespaces=None):
获取第一个寻找到的子节点
"""Find first matching element by tag name or path.
*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.
Return the first matching element, or None if no element was found.
"""
return ElementPath.find(self, path, namespaces)
def findtext(self, path, default=None, namespaces=None):
获取第一个寻找到的子节点的内容
"""Find text for first matching element by tag name or path.
*path* is a string having either an element tag or an XPath,
*default* is the value to return if the element was not found,
*namespaces* is an optional mapping from namespace prefix to full name.
Return text content of first matching element, or default value if
none was found. Note that if an element is found having no text
content, the empty string is returned.
"""
return ElementPath.findtext(self, path, default, namespaces)
def findall(self, path, namespaces=None):
获取所有的子节点
"""Find all matching subelements by tag name or path.
*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.
Returns list containing all matching elements in document order.
"""
return ElementPath.findall(self, path, namespaces)
def iterfind(self, path, namespaces=None):
获取所有指定的节点,并创建一个迭代器(可以被for循环)
"""Find all matching subelements by tag name or path.
*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.
Return an iterable yielding all matching elements in document order.
"""
return ElementPath.iterfind(self, path, namespaces)
def clear(self):
清空节点
"""Reset element.
This function removes all subelements, clears all attributes, and sets
the text and tail attributes to None.
"""
self.attrib.clear()
self._children = []
self.text = self.tail = None
def get(self, key, default=None):
获取当前节点的属性值
"""Get element attribute.
Equivalent to attrib.get, but some implementations may handle this a
bit more efficiently. *key* is what attribute to look for, and
*default* is what to return if the attribute was not found.
Returns a string containing the attribute value, or the default if
attribute was not found.
"""
return self.attrib.get(key, default)
def set(self, key, value):
为当前节点设置属性值
"""Set element attribute.
Equivalent to attrib[key] = value, but some implementations may handle
this a bit more efficiently. *key* is what attribute to set, and
*value* is the attribute value to set it to.
"""
self.attrib[key] = value
def keys(self):
获取当前节点的所有属性的 key
"""Get list of attribute names.
Names are returned in an arbitrary order, just like an ordinary
Python dict. Equivalent to attrib.keys()
"""
return self.attrib.keys()
def items(self):
获取当前节点的所有属性值,每个属性都是一个键值对
"""Get element attributes as a sequence.
The attributes are returned in arbitrary order. Equivalent to
attrib.items().
Return a list of (name, value) tuples.
"""
return self.attrib.items()
def iter(self, tag=None):
在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
"""Create tree iterator.
The iterator loops over the element and all subelements in document
order, returning all elements with a matching tag.
If the tree structure is modified during iteration, new or removed
elements may or may not be included. To get a stable set, use the
list() function on the iterator, and loop over the resulting list.
*tag* is what tags to look for (default is to return all elements)
Return an iterator containing all the matching elements.
"""
if tag == "*":
tag = None
if tag is None or self.tag == tag:
yield self
for e in self._children:
yield from e.iter(tag)
# compatibility
def getiterator(self, tag=None):
# Change for a DeprecationWarning in 1.4
warnings.warn(
"This method will be removed in future versions. "
"Use \'elem.iter()\' or \'list(elem.iter())\' instead.",
PendingDeprecationWarning, stacklevel=2
)
return list(self.iter(tag))
def itertext(self):
在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
"""Create text iterator.
The iterator loops over the element and all subelements in document
order, returning all inner text.
"""
tag = self.tag
if not isinstance(tag, str) and tag is not None:
return
if self.text:
yield self.text
for e in self:
yield from e.itertext()
if e.tail:
yield e.tail
复制代码
2.1:遍历XML文档中的所有内容
#遍历xml文档中的所有内容
from xml.etree import ElementTree as ET
"""
解析方式-
"""
#打开文件,读取XML内容
# str_xml = open(\'lcj.xml\',\'r\').read()
# #将字符串解析XML特殊对象,root代指XML根节点
# root = ET.XML(str_xml)
# print(root) #<Element \'data\' at 0x0000000000DFCF48>
"""
解析方式二
"""
#直接解析xml文件
tree = ET.parse(\'lcj.xml\')
#获取xml文件的根节点
tree = tree.getroot()
print(tree) #<Element \'data\' at 0x0000000000D70A98>
#遍历XML文档的第二层
for ww in tree:
#第二层节点的标签名称tag和标签属性:attrib
print(ww.tag,ww.attrib)
# country {\'tel\': \'13520617350\', \'name\': \'CTO\', \'age\': \'18\'}
# country {\'tel\': \'13520617350\', \'name\': \'CEO\'}
# country{\'tel\': \'13520617350\', \'name\': \'COO\'}
#遍历XML文档的第三层
for i in ww:
#遍历第二层节点的标签名和内容
print(i.tag,i.text)
# rank 69
# year 2026
# gdppc 13600
# neighbor None
# neighbor None
2.2 遍历XML中指定的节点
解析方式一:
from xml.etree import ElementTree as ET #导入模块
#打开文件,读取XML内容
str_xml = open(\'lcj.xml\',\'r\').read()
#将字符串解析XML特殊对象,root代指XML根节点
root = ET.XML(str_xml)
#顶层标签
print(root.tag) #data
#遍历XML文档中所有的year节点
for h in root.iter(\'year\'):
#节点的标签和内容
print(h.tag,h.text)
# year 2023
# year 2026
# year 2026
解析方式二:parse
from xml.etree import ElementTree as ET #导入模块
print("解析方式二")
#直接解析xml文件
tree = ET.parse(\'lcj.xml\')
#获取xml文件中的根节点
root = tree.getroot()
print(root) #<Element \'data\' at 0x0000000000D70A98>
#顶层标签
print(root.tag) #data
#遍历XML文档中所有的year节点
for h in root.iter(\'year\'):
#节点的标签和内容
print(h.tag,h.text)
# year 2023
# year 2026
# year 2026
2.3 修改节点内容
如有修改的节点时,均是在内存中进行,其不会影响文件中的内容,所以,如果想要修改,则需要重新将内存中的内容写入文件
A:解析字符串方式、修改、保存【两步拿到Element】
from xml.etree import ElementTree as ET
print("解析方式一")
#打开文件,读取XML内容
str_xml = open(\'lcj.xml\',\'r\').read()
#将字符串解析XML特殊对象,root代指XML根节点
root = ET.XML(str_xml)
#顶层标签
print(root.tag) #data
#设置属性
for node in root.iter(\'year\'): #iter循环迭代
new_year = int(node.text) +1 #将内存中存在year自增加一
node.text = str(new_year) #写入xml内存中
#设置属性
node.set(\'name\',\'lcj\') #修改内存中姓名和年龄
node.set(\'age\',\'19\')
#删除属性
# del node.attrib[\'age\']
#root=内存中的根节点,将root放到ElementTree里面,ElementTree赋值给tree
tree = ET.ElementTree(root)
#将year自增一从内存中保存至一个新文件中cj02.xml,并按照utf-8编码格式写入
tree.write(\'lcj06.xml\',encoding=\'utf-8\')
ww = open("lcj06.xml",\'r\').read() #将新生成的lcj04.xml文件在控制到输出
print(ww)
解析方式二:
from xml.etree import ElementTree as ET
print("解析方式二")
#直接解析xml文件
tree = ET.parse(\'lcj.xml\')
#获取xml文件中的根节点
root = tree.getroot()
#顶层标签
print(root.tag) #data
#循环XML文档中所有的year节点
for node in root.iter(\'year\'):
#将year节点中的内容自增一
new_year = int(node.text)+1
node.text = str(new_year)
print(node.text)
# 2024 2027 2027 文件中year:一次增加一
tree = ET.ElementTree(root)
#将year自增一从内存中保存至一个新文件中cj02.xml,并按照utf-8编码格式写入
tree.write(\'lcj02.xml\',encoding=\'utf-8\')
#将lcj02.xml文件输出值控制台
ww = open(\'lcj02.xml\',\'r\').read()
print(ww)
B:解析文件方式、修改、保存
from xml.etree import ElementTree as ET
print("解析方式二")
#直接解析xml文件
tree = ET.parse(\'lcj.xml\')
#获取xml文件中的根节点
root = tree.getroot()
#顶层标签
print(root.tag) #data
#设置属性
for node in root.iter(\'year\'): #iter循环迭代
new_year = int(node.text) +1 #将内存中存在year自增加一
node.text = str(new_year) #写入xml内存中
#设置属性
node.set(\'name\',\'lcj\') #修改内存中姓名和年龄
node.set(\'age\',\'19\')
#删除属性
del node.attrib[\'age\']
#将year自增一从内存中保存至一个新文件中cj02.xml,并按照utf-8编码格式写入
tree.write(\'lcj05.xml\',encoding=\'utf-8\')
ww = open("lcj05.xml",\'r\').read() #将新生成的lcj04.xml文件在控制到输出
print(ww)
C:删除节点
解析字符串方式打开,删除,保存
from xml.etree import ElementTree as ET
print(\'解析字符串方式打开\')
#打开文件,读取XML内容
str_xml = open(\'lcj.xml\',\'r\').read()
#将字符串解析成xml特殊对象,root代指XML文件的根节点
root = ET.XML(str_xml)
#操作
#顶层标签
print(root.tag) #data
#遍历data下的所有country节点
for country in root.findall(\'country\'):
#获取每一个country节点下的rank节点的内容
rank = int(country.find(\'rank\').text)
if rank > 50:
#删除指定country节点,rank大于50的
root.remove(country)
#保存文件
tree = ET.ElementTree(root)
tree.write(\'lcj07.xml\',encoding=\'utf-8\')
ww = open(\'lcj07.xml\',\'r\').read()
print(ww)
解析文件方式打开,删除,保存
from xml.etree import ElementTree as ET
#直接解析xml文件
tree = ET.parse(\'lcj.xml\')
#获取xml文件根节点
root = tree.getroot()
#操作
#顶层标签
print(root.tag) #data
#遍历data下的所有country节点
for country in root.findall(\'country\'):
#获取每一个country节点下的rank节点的内容
rank = int(country.find(\'rank\').text)
if rank > 50:
#删除指定country节点,rank大于50的
root.remove(country)
#保存文件
# tree = ET.ElementTree(root) #此处:在以字符串方式打开文件的需转换
tree.write(\'lcj08.xml\',encoding=\'utf-8\')
ww = open(\'lcj08.xml\',\'r\').read()
print(ww)
3、创建XML文档
自闭合:创建一个空的xml文件,中间没有内容
创建xml文档方式一:
from xml.etree import ElementTree as ET
#创建根节点
root = ET.Element("home") #Element类,创建一个对象Element("home"),home:节点名
#在根节点下添加第一层节点为大son1
son1 = ET.Element("son",{"name":\'儿one\'}) #创建节点对象Element()
#创建第二层节点小son2
son2 = ET.Element("son",{"name":\'儿two\'})
#在第一层大儿子中创建两个孙子
grandson1 = ET.Element(\'grandson\',{"name":\'lcj11\'})
grandson2 = ET.Element(\'grandson\',{"name":\'lcj12\'})
grandson3 = ET.Element(\'grandson\',{"name":\'lcj13\'})
#获取顶层标签
print(root.tag)
#将孙子添加至son1中
son1.append(grandson1)
son1.append(grandson2)
son1.append(grandson3)
#把大儿子添加至根节点中root
root.append(son1)
#将节点写入文件
tree = ET.ElementTree(root)
tree.write(\'ooo.xml\',encoding=\'utf-8\', short_empty_elements=False)
ww = open(\'ooo.xml\',\'r\').read()
print(ww)
创建xml文档方式二:makeelement
from xml.etree import ElementTree as ET
#创建根节点
root = ET.Element("home") #Element类,创建一个对象Element("home"),home:节点名
#在根节点下添加第一层节点为大son1
# son1 = ET.Element("son",{"name":\'儿one\'}) #创建节点对象Element() 方式一
son1 = root.makeelement(\'son\',{\'name\':\'儿1\'}) #方式二
#创建第二层节点小son2
# son2 = ET.Element("son",{"name":\'儿two\'}) 方式一
son2 = root.makeelement(\'son\',{\'name\':\'儿2\'}) #方式二
#在第一层大儿子中创建两个孙子
# grandson1 = ET.Element(\'grandson\',{"name":\'lcj11\'}) 方式一
grandson1 = son1.makeelement(\'grandson\',{\'name\':\'儿11\'}) #方式二
# grandson2 = ET.Element(\'grandson\',{"name":\'lcj12\'}) 方式一
grandson2 = son1.makeelement(\'grandson\',{"name":\'lcj12\'}) #方式二
# grandson3 = ET.Element(\'grandson\',{"name":\'lcj13\'}) 方式一
grandson3 = son1.makeelement(\'grandson\',{"name":\'lcj13\'}) #方式三
#获取顶层标签
print(root.tag)
#将孙子添加至son1中
son1.append(grandson1)
son1.append(grandson2)
son1.append(grandson3)
#把大儿子添加至根节点中root
root.append(son1)
#将节点写入文件
tree = ET.ElementTree(root)
tree.write(\'oooo.xml\',encoding=\'utf-8\', short_empty_elements=False)
创建xml文档方式三:xml_declaration=True 添加xml版本注释
from xml.etree import ElementTree as ET
#创建根节点
root = ET.Element("home") #Element类,创建一个对象Element("home"),home:节点名
#在根节点下添加第一层节点为大son1
#SubElement:创建Element对象,内部在进行append将数据写入内存
son1 = ET.SubElement(root,"son",attrib={"name":\'儿one\'}) #创建节点对象Element()
#创建第二层节点小son2
son2 = ET.SubElement(root,"son",{"name":\'儿two\'})
#在第一层大儿子中创建两个孙子
grandson1 = ET.SubElement(son1,"age",attrib={"name":\'lcj11\'})
grandson2 = ET.SubElement(son1,"age",attrib={"name":\'lcj12\'})
#获取顶层标签
print(root.tag)
#将孙子添加至son1中
son1.append(grandson1)
son1.append(grandson2)
#把大儿子添加至根节点中root
root.append(son1)
#将节点写入文件
tree = ET.ElementTree(root)
#xml_declaration=True 添加XML版本注释
tree.write(\'ool.xml\',encoding=\'utf-8\', xml_declaration=True,short_empty_elements=False)
ww = open(\'ool.xml\',\'r\').read()
print(ww)
由于原生保存的XML文件时默认是无缩进,如果想要设置缩进的话,需要修改保存方式:
from xml.etree import ElementTree as ET
from xml.dom import minidom
def prettify(elem):
"""将节点转换成字符串,并添加缩进。
"""
rough_string = ET.tostring(elem, \'utf-8\') #tostring将节点转换至字符存类型,并按utf-8编码转换
reparsed = minidom.parseString(rough_string) #通过对象格式化
return reparsed.toprettyxml(indent="\\t") #添加缩进
# 创建根节点
root = ET.Element("famliy")
# 创建大儿子
# son1 = ET.Element(\'son\', {\'name\': \'儿1\'})
son1 = root.makeelement(\'son\', {\'name\': \'儿1\'})
# 创建小儿子
# son2 = ET.Element(\'son\', {"name": \'儿2\'})
son2 = root.makeelement(\'son\', {"name": \'儿2\'})
# 在大儿子中创建两个孙子
# grandson1 = ET.Element(\'grandson\', {\'name\': \'儿11\'})
grandson1 = son1.makeelement(\'grandson\', {\'name\': \'儿11\'})
# grandson2 = ET.Element(\'grandson\', {\'name\': \'儿12\'})
grandson2 = son1.makeelement(\'grandson\', {\'name\': \'儿12\'})
son1.append(grandson1)
son1.append(grandson2)
# 把儿子添加到根节点中
root.append(son1)
root.append(son1)
#执行prettify方法,将根节点传进prettify方法,并赋值给一个字符串
raw_str = prettify(root)
f = open("test.xml",\'w\',encoding=\'utf-8\')
f.write(raw_str)
f.close()
www = open("test.xml",\'r\',encoding="utf-8").read()
print(www)
4、XML空间命令规范:
详细介绍,猛击这里
from xml.etree import ElementTree as ET
ET.register_namespace(\'com\',"http://www.company.com") #some name
# build a tree structure
root = ET.Element("{http://www.company.com}STUFF")
body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF", attrib={"{http://www.company.com}hhh": "123"})
body.text = "STUFF EVERYWHERE!"
# wrap it in an ElementTree instance, and save as XML
tree = ET.ElementTree(root)
tree.write("page.xml",
xml_declaration=True,
encoding=\'utf-8\',
method="xml")
三、requests
Python标准库中提供了:urllib等模块以供http请求,但是,他的API台slow,他是为另外一个时代、另外一个互联网所创建的,需要巨量的工作,来完成最简单的任务。
1、发送GET请求:
import urllib.request
f = urllib.request.urlopen(\'http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508\')
result = f.read().decode(\'utf-8\')
print(result)
# <?xml version="1.0" encoding="utf-8"?>
# <string xmlns="http://WebXml.com.cn/">Y</string>
2、发送POST请求:
#post请求
import urllib.request #导入模块
req = urllib.request.Request(\'http://www.example.com/\') #
req.add_header(\'Referer\', \'http://www.python.org/\')
r = urllib.request.urlopen(req)
result = r.read().decode(\'utf-8\')
print(result)
# <body>
# <div>
# <h1>Example Domain</h1>
# <p>This domain is established to be used for illustrative examples in documents. You may use this
# domain in examples without prior coordination or asking for permission.</p>
# <p><a href="http://www.iana.org/domains/example">More information...</a></p>
# </div>
# </body>
# </html>
Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。
1)安装模块:
2)、使用模块
get请求:无参数
import requests #导入requests模块
ret = requests.get(\'https://github.com/timeline.json\') #获取get请求地址
print(ret.url) #打印请求url
print(ret.text) #打印usr返回的内容
# https://github.com/timeline.json
# {"message":"Hello there, wayfaring stranger. If you’re reading this then you probably didn’t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}
get请求:有参数
import requests #导入模块
payload = {\'key1\': \'value1\', \'key2\': \'value2\'} #动态参数
ret = requests.get("http://httpbin.org/get", params=payload)
print(ret.url) #返回请求URL
print(ret.text) #打印返回的请求内容
post请求:无参数
import requests
payload = {\'key1\': \'value1\', \'key2\': \'value2\'}
ret = requests.post("http://httpbin.org/post", data=payload)
print(ret.text)
post请求:带参数(请求体、请求头)
import requests
import json
#发送请求头,请求体
url = \'https://api.github.com/some/endpoint\'
payload = {\'some\': \'data\'} #请求体
headers = {\'content-type\': \'application/json\'} #请求头
ret = requests.post(url, data=json.dumps(payload), headers=headers)
print(ret.text)
print(ret.cookies)
# {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
# <RequestsCookieJar[]>
其他请求:
requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.head(url, **kwargs)
requests.delete(url, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.options(url, **kwargs)
# 以上方法均是在此方法的基础上构建
requests.request(method, url, **kwargs
更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/
3)http请求和XML实例
实例:检测QQ账号是在线
import urllib
import requests
from xml.etree import ElementTree as ET
# 使用内置模块urllib发送HTTP请求,或者XML格式内容
"""
f = urllib.request.urlopen(\'http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508\')
result = f.read().decode(\'utf-8\')
"""
# 使用第三方模块requests发送HTTP请求,或者XML格式内容
r = requests.get(\'http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508\')
result = r.text
# 解析XML格式内容
node = ET.XML(result)
# 获取内容
if node.text == "Y":
print("在线")
else:
print("离线")
实例:查看火车停靠信息
import urllib
import requests
from xml.etree import ElementTree as ET
# 使用内置模块urllib发送HTTP请求,或者XML格式内容
"""
f = urllib.request.urlopen(\'http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=\')
result = f.read().decode(\'utf-8\')
"""
# 使用第三方模块requests发送HTTP请求,或者XML格式内容
r = requests.get(\'http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=\')
result = r.text
# 解析XML格式内容
root = ET.XML(result)
for node in root.iter(\'TrainDetailInfo\'):
print(node.find(\'TrainStation\').text,node.find(\'StartTime\').text,node.tag,node.attrib)
注:更多接口猛击这里
五、shutil
高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
1、将文件内容拷贝到另一个文件中
import shutil
#将ool.xml文件中的内容,复制到新文件kaobei.xml中
shutil.copyfileobj(open(\'ool.xml\',\'r\'),open(\'kaobei.xml\',\'w\'))
f =open("kaobei.xml",\'r\').read()
print(f)
2、shutil.copyfile(src, dst)
拷贝文件
import shutil
#将ool.xml文件copy至新文件oox.xml中
shutil.copyfile(\'ool.xml\',\'oox.xml\')
f = open("oox.xml",\'r\').read()
print(f)
3、shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变
shutil.copymode(\'f1.log\', \'f2.log\')
4、shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copystat(\'f1.log\', \'f2.log\')
5、shutil.copy(src, dst)
拷贝文件和权限
import shutil
shutil.copy(\'f1.log\', \'f2.log\')
6、shutil.copy2(src, dst)
拷贝文件和状态信息
import shutil
shutil.copy2(\'f1.log\', \'f2.log\')
7、shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
import shutil
shutil.copytree(\'folder1\', \'folder2\', ignore=shutil.ignore_patterns(\'*.pyc\', \'tmp*\')) #忽略.pyc结尾和tmp*开头的文件
import shutil
shutil.copytree(\'f1\', \'f2\', symlinks=True, ignore=shutil.ignore_patterns(\'*.pyc\', \'tmp*\'))
8、shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
import shutil
shutil.rmtree(\'folder1\')
9、shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名
import shutil
shutil.move(\'folder1\', \'folder3\')
10,shutil.make_archive(base_name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
创建压缩包并返回文件路径,例如:zip、tar
- base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/ - format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
- root_dir: 要压缩的文件夹路径(默认当前目录)
- owner: 用户,默认当前用户
- group: 组,默认当前组
- logger: 用于记录日志,通常是logging.Logger对象
import shutil
#将当前目录下的kaobei01文件,打包至D:\\S13_code\\day7_zuoye目录
ret = shutil.make_archive("kaobei01",\'gztar\',root_dir=\'D:\\S13_code\\day7_zuoye\')
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
1)ZipFile模块
import zipfile
#压缩文件
z = zipfile.ZipFile(\'test.zip\',\'w\') #创建一个空的压缩文件名test.zip
#将如下文件压缩至test.zip文件中
z.write(\'oox.xml\')
z.write(\'ool.xml\')
z.close()
将文件追加至已经存在的压缩文件中
import zipfile
#a模式:将文件lcj07.xml,lcj06.xml追加至压缩文件test.zip
z = zipfile.ZipFile("test.zip",\'a\')
z.write("lcj07.xml")
z.write("lcj06.xml")
z.close()
解压缩文件:
#解压缩
z = zipfile.ZipFile(\'test.zip\', \'r\')
z.extractall() #解压所有文件
z.close()
for循环对压缩文件中的文件进行遍历输出
import zipfile
z=zipfile.ZipFile("test.zip",\'r\')
#通过for循环,对test.zip压缩文件中的存在文件进行遍历输出
for item in z.namelist():
print(item,type(item))
z.close()
# ooo.xml <class \'str\'>
# ool.xml <class \'str\'>
# lcj07.xml <class \'str\'>
# lcj06.xml <class \'str\'>
对单个文件进行解压:extract 解压单个文件
import zipfile
z=zipfile.ZipFile("test.zip",\'r\')
#通过for循环,对test.zip压缩文件中的存在文件进行遍历输出
# for item in z.namelist():
# print(item,type(item))
z.extract(\'ooo.xml\') #extract:解压压缩文件夹test.zip中,单个ooo.xml至当前目录
z.close()
2) TarFile模块
tar:压缩文件
import tarfile #压缩文件 tar = tarfile.open(\'xiaoluo.tar\',\'w\')
#ool.xml:此处可添加压缩文件存在的绝对地址,如:/Users/wupeiqi/PycharmProjects/bbs2.log tar.add(\'ool.xml\',arcname=\'www.log\') #将原件名改成www.log并存在xiaoluo.tar tar.add(\'oox.xml\',arcname=\'fff.log\') tar.close()
tar:解压文件 extractall:解压所有文件
import tarfile
tar = tarfile.open(\'xiaoluo.tar\',\'r\')
tar.extractall() # 可设置解压地址
tar.close()
tar:解压指定文件 【通过字符串赋值给变量,由变量再向tar包中匹配文件进行解压】
import tarfile
tar= tarfile.open("lcj.tar",\'r\')
for item in tar.getmembers(): #getmembers:获取当前tar包中所有成员
print(item,type(item))
#获取所有对象
# <TarInfo \'lcj01.xml\' at 0xb8bd90> <class \'tarfile.TarInfo\'>
# <TarInfo \'test01.xml\' at 0xb8be58> <class \'tarfile.TarInfo\'>
#getmember:通过字符串获取对象表达式
obj = tar.getmember("lcj01.xml") #将字符串赋值给一个变量
print(obj,type(obj))
# <TarInfo \'lcj01.xml\' at 0xd9a9a8> <class \'tarfile.TarInfo\'>
# <TarInfo \'test01.xml\' at 0xd9ab38> <class \'tarfile.TarInfo\'>
# <TarInfo \'lcj01.xml\' at 0xd9a9a8> <class \'tarfile.TarInfo\'>
tar.extract(obj) #解压文件 通过变量找到tar包中匹配的对象,并解压
tar.close()
六、系统命令
可执行shell命令的相关模块和函数有:
- os.system
- os.spawn*
- os.popen* --废弃
- popen2.* --废弃
- commands.* --废弃,3.x中被移除
import commands
result = commands.getoutput(\'cmd\')
result = commands.getstatus(\'cmd\')
result = commands.getstatusoutput(\'cmd\')
以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。
1)、call命令
执行命令,并返回状态码
import subprocess
ret = subprocess.call(["ls", "-l"], shell=False) #需在linux环境下进行,
ret = subprocess.call("ls -l", shell=True)
2)、check_all
执行命令,如果执行状态码是0,则返回0,否则抛出异常
import subprocess
subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)
3)、check_output
执行命令,如果执行状态码是0,则返回执行结果,否则抛出异常
import subprocess
subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)
4)、subprocess.Popen(...)
Popen:是call check_call check_output中最底层的代码
- args:shell命令,可以是字符串或者序列类型(如:list,元组)
- bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
- preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
- close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。 - shell:同上
- cwd:用于设置子进程的当前目录
- env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
- universal_newlines:不同系统的换行符不同,True -> 同意使用 \\n
- startupinfo与createionflags只在windows下有效
将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)
终端输入的命令分为两种:
- 输入即可得到输出,如:ifconfig
- 输入进行某环境,依赖再输入,如:python3
import subprocess
obj = subprocess.Popen("mkdir t3", shell=True, cwd=\'/home/dev\',) #设置一个路径
subprocess用法一:添加内容、写入
import subprocess
obj = subprocess.Popen(["python"], #中端输出python,进入python解析器,并获取obj对象
stdin=subprocess.PIPE, #写东西的管道
stdout=subprocess.PIPE, #获取结果的管道
stderr=subprocess.PIPE, #获取错误的管道
universal_newlines=True)
obj.stdin.write("print(1)\\n") #管道中写入数据
obj.stdin.write("print(2)")
obj.stdin.close()
cmd_out = obj.stdout.read() #在输出管道读取内容
obj.stdout.close()
#
cmd_error = obj.stderr.read() #如出错,在错误管道中读取内容
obj.stderr.close()
print(cmd_out) #输出已拿到的数据
print(cmd_error) #输出错误内容数据
# 1
# 2
subprocess用法二(communicate):
import subprocess
obj = subprocess.Popen(["python"], #中端输出python,进入python解析器,并获取obj对象
stdin=subproce以上是关于python_day7模块configparserXMLrequestsshutil系统命令-面向对象之篇的主要内容,如果未能解决你的问题,请参考以下文章
Python全栈--7.3--模块补充configparser--logging--subprocess--os.system--shutil