需求:当我们修改,删除xml文件中的数据后,这个操作是在内存中进行的,所以需要将内存中的数据保存到文件中
下面学习文件保存指令:
from xml.etree import ElementTree as ETcontent = """<data><country name="Liechtenstein"><rank>2</rank><year>2023</year><gdppc>141100</gdppc><neighbor direction="E" name="Austria" /><neighbor direction="W" name="Switzerland" /></country><country name="Panama"><rank>69</rank><year>2026</year><gdppc>13600</gdppc><neighbor direction="W" name="Costa Rica" /><neighbor direction="E" name="Colombia" /></country></data>"""root = ET.XML(content)# 保存文件tree = ET.ElementTree(root)tree.write("new.xml", encoding='utf-8')# 这个第一个属性实际上是filepath,第二个属性是编码
