python基础篇【第七篇】模块补充、xml操作

一、ConfigParser模块

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

配置文件的格式是: []包含的叫section,    section 下有option=value这样的键值

[section1]
k1 = v1
k2:10
 
[section2]
k1 = v1

读取配置文件:

-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型

写文件:

-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
  需要调用write将内容写入配置文件。

如以下实例:

复制代码
 1 import configparser
 2 #生成config对象
 3 config = configparser.ConfigParser()
 4 config.read('conf')  #用config对象读取配置文件  
 5 
 6 secs=config.sections()  #以列表的形式返回所有的section
 7 print(secs)
 8 
 9 #打印结果
10 ['section1', 'section2']
11 
12 options=config.options("section1")  #得到指定section的所有option 
13 print(options)
14 #显示结果
15 ['k1', 'k2']
16 
17 item_list = config.items('section1') #得到指定section的所有键值对
18 print(item_list)
19 #显示结果
20 [('k1', 'v1'), ('k2', 'v2')]
21 
22 str_val = config.get("section1", "k1")   #指定section,option读取值 
23 int_val = config.getint("section1", "k2")  #用getint   k2必须为数字
24 print(str_val)
25 print(int_val)
26 #显示结果
27 v1
28 10
29 
30 
31 config.set("section1","k1","value1")  #更新指定section,option的值
32 config.set("section2","new_k","new_v")  #写入指定section增加新option和值
33 config.add_section("new_section")    #增加新的section  
34 config.set("new_section","new_k1","new_v1")   #添加新的option和值
35 config.write(open("conf","w"))    #写到配置文件
36 
37 #文件内容
38 [section1]
39 k1 = value1
40 k2 = 10
41 
42 [section2]
43 k1 = v1
44 new_k = new_v
45 
46 [new_section]
47 new_k1 = new_v1
复制代码

 

 

二、执行系统命令 

可以执行shell命令的相关模块和函数有:

  • os.system
  • os.spawn*
  • os.popen*          --废弃
  • popen2.*           --废弃
  • commands.*      --废弃,3.x中被移除

以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能,如下:

call

执行命令,返回状态返回值,

ret = subprocess.call(["ipconfig", "-all"], shell=False)
ret = subprocess.call("ipconfig -all", shell=True)

shell=True,允许命令是字符串形式,默认是False,命令是列表的形式书写

check_call

执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)   #这个状态码返回时是1 ,系统直接报错

subprocess.Popen(...)

用于执行复杂的系统命令

参数:

  • 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)
import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',) #在/home/dev/下创建t3目录

 

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')
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
View Code
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n ')
obj.stdin.write('print 2 \n ')
obj.stdin.write('print 3 \n ')
obj.stdin.write('print 4 \n ')

out_error_list = obj.communicate()
print out_error_list
View Code
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_error_list = obj.communicate('print "hello"')
print out_error_list
View Code

 

 

三、shutil

高级的 文件、文件夹、压缩包 处理模块

shutil模块提供了大量的文件的高级操作。特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作

shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中,可以部分内容

 

import shutil
shutil.copyfileobj(open('xo.xml','r'),open('data_new.xml','w'))
#把xo.xml里的内容copy到data_new.xml文件中,如果data_new.xml文件不存在就先创建再copy

 

shutil.copyfile(src, dst)

直接拷贝文件,如果dst存在的话,会被覆盖掉

复制代码
import shutil
import os

shutil.copyfile('data_new.xml','data_new2.xml')

result = os.listdir(os.path.dirname(__file__))
for i in result:
    print(i)
# #执行后会在当前目录下生成一个文件
# data_new2.xml
复制代码

 

shutil.copymode(src, dst)

拷贝文件权限,属主、属组和文件内容均不变。

 

shutil.copystat(src, dst)

 拷贝文件状态信息,状态信息包括: atime , mtime, flags, mode bits

 

shutil.copy()

拷贝文件和权限

复制代码
import shutil
import os
shutil.copy('data_new.xml','data_new2.xml')
print(os.stat("data_new.xml"))
print(os.stat('data_new2.xml'))

#显示结果
os.stat_result(st_mode=33206, st_ino=844424930174209, st_dev=2457783243, st_nlink=1, st_uid=0, st_gid=0, st_size=745, st_atime=1466501454, st_mtime=1466501454, st_ctime=1466501454)
os.stat_result(st_mode=33206, st_ino=7599824371229949, st_dev=2457783243, st_nlink=1, st_uid=0, st_gid=0, st_size=745, st_atime=1466501747, st_mtime=1466502010, st_ctime=1466501747)
复制代码

 

shutil.copy2(src, dst)

拷贝文件以及文件的状态信息

复制代码
shutil.copy2('data_new.xml','data_new2.xml')
print(os.stat("data_new.xml"))
print(os.stat('data_new2.xml'))

#显示结果 atime mtime 都一样
os.stat_result(st_mode=33206, st_ino=844424930174209, st_dev=2457783243, st_nlink=1, st_uid=0, st_gid=0, st_size=745, st_atime=1466501454, st_mtime=1466501454, st_ctime=1466501454)
os.stat_result(st_mode=33206, st_ino=7599824371229949, st_dev=2457783243, st_nlink=1, st_uid=0, st_gid=0, st_size=745, st_atime=1466501454, st_mtime=1466501454, st_ctime=1466501747)
复制代码

 

shutil.ignore_patters(*patterns)  

忽略某匹配模式的文件拷贝,生成一个函数,可以作为调用copytree()的ignore参数。

需要结合shutil.copytree(src , dst,symlinks=False, ignore=None)

shutil.copytree('dir1','dir2', ignore=shutil.ignore_patterns('*.xml'))
#把dir1中的文件过滤掉.xml文件,拷贝到dir2目录中,前提dir2目录不能存在,否则报错

 

shutil.rmtree(path[, ignore_error[,noerror]])  

递归方式删除文件 

shutil.rmtree("dir1")

 

shutil.move(src, dst)

递归方式移动(重命名)文件/文件夹,   和shell中的mv命令一样

复制代码
>>> os.listdir('.')
['dir2', 'dir1']
>>> shutil.move('dir2','/tmp/dir_2')
'/tmp/dir_2'
>>> os.listdir('.')
['dir1']
>>> os.listdir('/tmp')
['dir_2', 'test.py', '1_bak', 'hsperfdata_root']
复制代码

 

shutil.make_archive(base_name, format,root_dir=None, base_dir=None, verbose=0,dry_run=0, owner=None, group=None, logger=None)

创建压缩包并返回文件路径,例如:zip、tar

  • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
    如:www                        =>保存至当前路径
    如:/Users/test/www =>保存至/Users/test/
  • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要压缩的文件夹路径(默认当前目录)
  • owner: 用户,默认当前用户
  • group: 组,默认当前组
  • logger: 用于记录日志,通常是logging.Logger对象
shutil.make_archive("dir1",'gztar')
#结果在当前目录中创建一个:
dir1.tar.gz

 

ZipFile模块

ZipFile模块是处理zip压缩包的模块,用于压缩和解压,添加和列出压缩包的内容。ZipFile是主要的类,其过程是讲每个文件以及相关的信息作为ZipInfo对象操作到ZipFile的成员,包括文件头信息和文件内容

tarfile模块

tarfile模块可以用于压缩/解压tar类型文件,并且支持进一步压缩tar.gz和tar.bz2文件,主要是调用open函数打开文件,并返回TarFile实例。

其实shutil对压缩包的处理就是调用ZipFile 和 TarFile两个模块来处理的。

复制代码
import zipfile
zip_file=zipfile.ZipFile("test.zip",'w')

zip_file.write("xml_test.py")
zip_file.write('ooo.xml')
zip_file.close()
#执行完之后发现当前目录中多了一个test.zip压缩包


#解压缩
zz=zipfile.ZipFile('test.zip',"r")
zz.extractall()    #把test.zip中的文件全部解压出来
zz.close()
复制代码

 

解压指定文件

复制代码
#想要解压缩某一个文件,首先要知道压缩包内包含什么文件。
zf = zipfile.ZipFile('test.zip','r')
#先使用namelist()方法来查看压缩包内的文件,返回一个列表的形式
result = zf.namelist()
for i in result:
    print(i)

#for循环,查看执行结果:
xml_test.py
ooo.xml


#解压s2_xml.py出来,先删除当前目录下的这个文件:
#而后使用extract()方法解压
zf.extract('xml_test.py')
复制代码

tarfile

复制代码
import tarfile
#打包
tar_file=tarfile.open('test.tar',"w")
tar_file.add("xml_test.py",arcname='xml_test.py')
tar_file.add("newnew.xml",arcname='new.xml')
tar_file.close()
#arcname是在包里的文件名字,打包后的文件名字可以和源文件名字不同

#删除原有的文件
tar_file = tarfile.open('test.tar','r')
tar_file.extractall()
tar_file.close()

#解压出来的newnew.xml变成new.xml
复制代码
#解压归档包里的某一个文件,还是首先要查看包里包含什么文件。使用getnames()方法,返回一个列表,而后使用extract()解压所需的单个文件
tar_file = tarfile.open('test.tar','r')

tar_file.extract('xml_test.py')

tar_file.close()

 

四、xml

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单

xml的格式如下,就是通过<>节点来区别数据结构的:

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

 

解析xml

from xml.etree import ElementTree as ET
tree = ET.parse('new.xml')
root = tree.getroot()   #获取文件根节点,
print(root)         #是一个Element对象

#返回结果
<Element 'data1' at 0x0000001F217744A8>

 

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

节点功能
View Code

 

遍历文档的所有内容

from xml.etree import ElementTree as ET
tree = ET.parse('new.xml')
root = tree.getroot()   #获取文件根节点,
print(root.tag)         #显示根节点
for child in root:       #偏历第二层的内容
    print(child.tag,child.attrib)   #
    for gradechild in child:   #遍历第三层的内容
        print(gradechild.tag, gradechild.text)
View Code

 

遍历xml文档中指定的节点:

from xml.etree import ElementTree as ET
tree = ET.parse('new.xml')
root = tree.getroot()   #获取文件根节点,
print(root.tag,root.attrib)   #打印标签和内容
for i in root:
    print(i.tag,i.attrib)
    for a in i.iter('year'):  #获取指定的‘year’节点的标签及内容
        print(a.tag,a.text)

#显示结果
data1 {'age': '19', 'title': 'CTO'}
country {'age': '18', 'name': 'Liechtenstein'}
year 2023
country {'name': 'Singapore'}
year 2026
country {'name': 'Panama'}
year 2026
Alex {'k1': 'v1'}
遍历指定节点

 

刚才说的都是的获取,现在来说说修改,xml修改也只是在内存中修改,如果需要保存修改内容,需把内存中数据写到文件中。

分为两种方式;解析字符串方式的修改保存,和直接修改文件方式保存

from xml.etree import ElementTree as ET
result_xml = open('new.xml','r',encoding='utf-8').read()
#找到根节点
root = ET.XML(result_xml)
print("根节点:%s"%root.tag)
print(root.tag,root.attrib)   #打印标签和属性
for i in root:
    print(i.tag,i.attrib)
    for a in i.iter('year'):  #获取指定的‘year’节点的标签及内容
       a.text=str(2038)

       #添加属性
       a.set("k1","v1")
       a.set("k2","v2")

       #删除属性
       del a.attrib['k1']
       print(a.tag,a.attrib,a.text,type(a.attrib))  #获取、标签、属性、内容以及类型
tree=ET.ElementTree(root)
tree.write("new2.xml",encoding="utf-8")
字符串方式
from xml.etree import ElementTree as ET
tree = ET.parse('new.xml')
root = tree.getroot()   #获取文件根节点,
print(root.tag,root.attrib)   #打印标签和属性
for i in root:
    print(i.tag,i.attrib)
    for a in i.iter('year'):  #获取指定的‘year’节点的标签及内容
       a.text=str(2038)

       #添加属性
       a.set("k1","v1")
       a.set("k2","v2")

       #删除属性
       del a.attrib['k1']
       print()
       print(a.tag,a.attrib,a.text,type(a.attrib))  #获取、标签、属性、内容以及类型
tree.write("new2.xml",encoding="utf-8")
文件方式

 

删除节点

from xml.etree import ElementTree as ET
tree = ET.parse('new.xml')
root = tree.getroot()   #获取文件根节点,
print(root.tag)         #显示根节点

for i in root:
    for a in i.findall("year"):    #删除所有节点下的 year
        i.remove(a)
tree.write("new2.xml",encoding="utf-8")

 

创建xml文件

#添加节点
from xml.etree import ElementTree as ET

#创建根节点
root=ET.Element("company")

#创建节点的部门
ceo =ET.Element("manager",{"ceo":"zhangsan"})

#创建coo
coo=ET.Element("manager",{"coo":"zhaosi"})

#创建cto
cto=ET.Element("manager",{"cto":"wanger"})

#创建部门cto
test=ET.Element("tech",{"test":"mazi"})
dev=ET.Element("tesch",{"dev":"lisi"})

cto.append(test)
cto.append(dev)

#再将manger添加到root下
root.append(ceo)
root.append(coo)
root.append(cto)

#写到文件中
tree=ET.ElementTree(root)
tree.write("manager.xml",encoding="utf-8",short_empty_elements=False)

#默认没有缩进
<company><manager ceo="zhangsan"></manager><manager coo="zhaosi"></manager><manager cto="wanger"><tech test="mazi"></tech><tesch dev="lisi"></tesch></manager></company>
创建节点方式一

创建xml方式二:

from xml.etree import ElementTree as ET

#创建根节点
root = ET.Element('company')

#创建高管
ceo = ET.SubElement(root,'manager',attrib={'ceo':'xiaomage'})
coo = ET.SubElement(root,'manager',attrib={'coo':'xiaoyang'})
cto = ET.SubElement(root,'manager',attrib={'cto':'laowang'})
#创建技术部门
dev = ET.SubElement(cto,'tech',{'dev':'xiaoli'})
ops = ET.SubElement(cto,'tech',{'ops':'xiaoqiang'})

cto.append(dev)
cto.append(ops)


tree = ET.ElementTree(root)  #生成文档对象
tree.write('company_v3.xml',encoding='utf-8',short_empty_elements=False)
创建xml方式二

创建xml方式三:

from xml.etree import ElementTree as ET

#创建根节点
root = ET.Element('company')

#创建高管
ceo = root.makeelement('manager',{'ceo':'xiaomage'})
coo = root.makeelement('manager',{'coo':'xiaoyang'})
cto = root.makeelement('manager',{'cto':'laowang'})

#创建技术部门
dev = cto.makeelement('tech',{'dev':'xiaoli'})
ops = cto.makeelement('tech',{'ops':'xiaoqiang'})

cto.append(dev)
cto.append(ops)

#添加部门到根节点
root.append(ceo)
root.append(coo)
root.append(cto)

tree = ET.ElementTree(root)
tree.write('company_v2.xml',encoding='utf-8',short_empty_elements=False)

#默认没有缩进:
<company><manager ceo="xiaomage"></manager><manager coo="xiaoyang"></manager><manager cto="laowang"><tech dev="xiaoli"></tech><tech ops="xiaoqiang"></tech></manager></company>
View Code

 

 

添加缩进

from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(string):
    '''
    将节点转换成字符串,并添加缩进
    :param string:
    :return:
    '''
    rough_string = ET.tostring(string,'utf-8')
    reparesd = minidom.parseString(rough_string)
    return reparesd.toprettyxml(indent='\t')

#创建根节点
root=ET.Element("company")

#创建节点的部门
ceo =ET.Element("manager",{"ceo":"zhangsan"})

#创建coo
coo=ET.Element("manager",{"coo":"zhaosi"})

#创建cto
cto=ET.Element("manager",{"cto":"wanger"})

#创建部门cto
test=ET.Element("tech",{"test":"mazi"})
dev=ET.Element("tesch",{"dev":"lisi"})

cto.append(test)
cto.append(dev)

#再将manger添加到root下
root.append(ceo)
root.append(coo)
root.append(cto)

string=prettify(root)
#写到文件中
f=open("manager2.xml","w",encoding="utf-8")
f.write(string)
f.close()



#显示结果
<?xml version="1.0" ?>
<company>
    <manager ceo="zhangsan"/>
    <manager coo="zhaosi"/>
    <manager cto="wanger">
        <tech test="mazi"/>
        <tesch dev="lisi"/>
    </manager>
</company>
View Code

 

转载于:https://www.cnblogs.com/tianjie0522/p/5605381.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python基础.doc》是一份讲解Python编程基础的文档。Python是一种简洁、易学、高效的编程语言,因此它成为了很多人入门编程的首选语言。 这份文档应该包含了Python的基本语法、变量、数据类型、运算符、流程控制、循环语句等内容。首先,它会详细介绍Python的注释规则,以及如何定义和使用变量。变量是存储数据的容器,它可以用于存储不同类型的数据,包括整数、浮点数、字符串等。接下来,文档应该解释各种常见的运算符,如算术运算符、比较运算符和逻辑运算符,以及它们的优先级和使用方法。 然后,文档应该涵盖Python中的条件语句和循环语句。条件语句如if语句和else语句,用于根据条件执行不同的代码块。循环语句如for循环和while循环,用于重复执行某些代码段。在解释这些语句时,应该给出一些实际的例子来帮助读者更好地理解。 此外,文档还应该介绍一些常用的内置函数和字符串操作方法。内置函数是Python提供的一些预先编写好的函数,可以直接使用,如print()和len()等。字符串操作方法主要是对字符串进行切片、连接、替换以及查找等操作。 最后,文档中还应该提供一些练习题或者编程示例,让读者能够通过实践来巩固所学的知识。 总之,《Python基础.doc》是一份详细讲解Python编程基础的文档,内容应该涵盖Python的基本语法、变量、数据类型、运算符、流程控制、循环语句等,并配有实例和练习题,以帮助读者更好地理解和掌握Python编程知识。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值