Python编程:xlm文件读写

简介: Python编程:xlm文件读写

xml文件增删改查


先引入解析xml文档的模块

import xml.etree.ElementTree as ET
tree = ET.parse("data.xml")  # 解析文档
root = tree.getroot()  # 获取根节点
print(root)
print(root.tag)

读取

# 遍历文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag, i.attrib, i.text)
# 只遍历year节点
for nood in root.iter("year"):
     print(nood.tag, nood.text)

修改

for node in root.iter("year"):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("update_by", "Tom")
tree.write("data.xml") # 修改后需要保存

删除

for country in root.findall("country"):
    rank = int(country.find("rank").text)
    if rank >50:
        root.remove(country)
tree.write("data.xml")  # 修改后需要保存

创建

new_xml = ET.Element("personlist")
person = ET.SubElement(new_xml, "person", attrib={"enrolled": "yes"})
name1 = ET.SubElement(person, "name")
name1.text = "Tom"
age = ET.SubElement(person, "age", attrib={"checked": "no"})
age.text = "33"
sex = ET.SubElement(person, "sex")
sex.text = 'man'
person2 = ET.SubElement(new_xml, "person", attrib={"enrolled": "no"})
name2 = ET.SubElement(person2, "name")
name2.text = "Jimi"
age2 = ET.SubElement(person2, "age")
age2.text = '19'
sex2 = ET.SubElement(person2, "sex")
sex2.text = "women"
et = ET.ElementTree(new_xml)  # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)  # 写入文件
ET.dump(new_xml)  # 打印生成的格式

help(ET)

"""
Each Element has a number of properties associated with it:
       'tag' - a string containing the element's name.
       'attrib' - a Python dictionary storing the element's attributes.
       'text' - a string containing the element's text content.
       'tail' - an optional string containing text after the element's end tag.
    class Element(builtins.object)
     |  
     |  append(...)
     |  
     |  clear(...)
     |  
     |  extend(...)
     |  
     |  find(...)
     |  
     |  findall(...)
     |  
     |  findtext(...)
     |  
     |  get(...)
     |  
     |  getchildren(...)
     |  
     |  getiterator(...)
     |  
     |  insert(...)
     |  
     |  items(...)
     |  
     |  iter(...)
     |  
     |  iterfind(...)
     |  
     |  itertext(...)
     |  
     |  keys(...)
     |  
     |  makeelement(...)
     |  
     |  remove(...)
     |  
     |  set(...)
    class ElementTree(builtins.object)
     |  
     |  Methods defined here:
     |  
     |  __init__(self, element=None, file=None)
     |  
     |  find(self, path, namespaces=None)
     |      Find first matching element by tag name or path.
     |      Return the first matching element, or None if no element was found.
     |  
     |  findall(self, path, namespaces=None)
     |      Find all matching subelements by tag name or path.
     |      Return list containing all matching elements in document order.
     |  
     |  findtext(self, path, default=None, namespaces=None)
     |      Find first matching element by tag name or path.
     |      Return the first matching element, or None if no element was found.
     |  
     |  getiterator(self, tag=None)
     |      # compatibility
     |  
     |  getroot(self)
     |      Return root element of this tree.
     |  
     |  iter(self, tag=None)
     |      Create and return tree iterator for the root element.
     |  
     |  iterfind(self, path, namespaces=None)
     |      Find all matching subelements by tag name or path.
     |      Return an iterable yielding all matching elements in document order.
     |  
     |  parse(self, source, parser=None)
     |      Load external XML document into element tree.
     |      Returns the root element of the given source document.
     |  
     |  write(self, file_or_filename, encoding=None, xml_declaration=None, default_namespace=None, method=None, *, short_empty_elements=True)
     |      Write element tree to a file as XML.
     |  ----------------------------------------------------------------------
FUNCTIONS
    Comment(text=None)
        Comment element factory.
    PI = ProcessingInstruction(target, text=None)
        Processing Instruction element factory.
    ProcessingInstruction(target, text=None)
        Processing Instruction element factory.
    SubElement(...)
    XML(text, parser=None)
        Parse XML document from string constant.
        Returns an Element instance.
    XMLID(text, parser=None)
        Parse XML document from string constant for its IDs      
        Returns an (Element, dict) tuple, in which the
        dict maps element id:s to elements.
    dump(elem)
        Write element tree or element structure to sys.stdout.
    fromstring = XML(text, parser=None)
        Parse XML document from string constant.
        Returns an Element instance.
    fromstringlist(sequence, parser=None)
        Parse XML document from sequence of string fragments.
        Returns an Element instance.
    iselement(element)
        Return True if *element* appears to be an Element.
    iterparse(source, events=None, parser=None)
        Incrementally parse XML document into ElementTree.
        Returns an iterator providing (event, elem) pairs.
    parse(source, parser=None)
        Parse XML document into element tree.
        Return an ElementTree instance.
    register_namespace(prefix, uri)
        Register a namespace prefix.
    tostring(element, encoding=None, method=None, *, short_empty_elements=True)
        Generate string representation of XML element.     
        Returns an (optionally) encoded string containing the XML data.
    tostringlist(element, encoding=None, method=None, *, short_empty_elements=True)
"""
相关文章
|
1天前
|
存储 Python
用Python实现批量下载文件——代理ip排除万难
用Python实现批量下载文件——代理ip排除万难
|
1天前
|
安全 数据处理 开发者
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
12 1
|
1天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
20 0
|
1天前
|
人工智能 数据挖掘 程序员
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
23 0
|
1天前
|
数据挖掘 索引 Python
Python 读写 Excel 文件
Python 读写 Excel 文件
7 0
|
1天前
|
数据安全/隐私保护 Python
Python文件与目录操作:面试中的高频考点
【4月更文挑战第15天】本文介绍了Python文件和目录操作的面试重点,包括文件的读写、目录遍历及权限管理。强调了文件关闭、异常处理、特殊文件判断以及权限位和权限字符串的理解。提供了代码示例,如读写文件、遍历目录和更改文件权限,帮助读者在面试中表现出色。掌握这些技能将对编程求职之路大有裨益。
15 0
|
2天前
|
API Python
Python模块化编程:面试题深度解析
【4月更文挑战第14天】了解Python模块化编程对于构建大型项目至关重要,它涉及代码组织、复用和维护。本文深入探讨了模块、包、导入机制、命名空间和作用域等基础概念,并列举了面试中常见的模块导入混乱、不适当星号导入等问题,强调了避免循环依赖、合理使用`__init__.py`以及理解模块作用域的重要性。掌握这些知识将有助于在面试中自信应对模块化编程的相关挑战。
17 0
|
3天前
|
Python
Python金融应用编程:衍生品定价和套期保值的随机过程
Python金融应用编程:衍生品定价和套期保值的随机过程
|
3天前
|
存储 监控 开发工具
对象存储OSS产品常见问题之python sdk中的append_object方法支持追加上传xls文件如何解决
对象存储OSS是基于互联网的数据存储服务模式,让用户可以安全、可靠地存储大量非结构化数据,如图片、音频、视频、文档等任意类型文件,并通过简单的基于HTTP/HTTPS协议的RESTful API接口进行访问和管理。本帖梳理了用户在实际使用中可能遇到的各种常见问题,涵盖了基础操作、性能优化、安全设置、费用管理、数据备份与恢复、跨区域同步、API接口调用等多个方面。
34 9
|
3天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
37 0