如何在 python 中更新/修改 XML 文件? [英] How to update/modify an XML file in python?

查看:36
本文介绍了如何在 python 中更新/修改 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文档,我想在它已经包含数据后进行更新.

I have an XML document that I would like to update after it already contains data.

我想过在 "a" (append) 模式下打开 XML 文件.问题是新数据会写在根结束标记之后.

I thought about opening the XML file in "a" (append) mode. The problem is that the new data will be written after the root closing tag.

如何删除文件的最后一行,然后从该点开始写入数据,然后关闭根标记?

How can I delete the last line of a file, then start writing data from that point, and then close the root tag?

当然我可以读取整个文件并进行一些字符串操作,但我认为这不是最好的主意..

Of course I could read the whole file and do some string manipulations, but I don't think that's the best idea..

感谢您的时间.

推荐答案

您绝对不应该这样做(见下文)的快速简便的方法是将整个文件读入一个列表使用 readlines() 的字符串.我写这篇文章是为了防止您正在寻找快速简便的解决方案.

The quick and easy way, which you definitely should not do (see below), is to read the whole file into a list of strings using readlines(). I write this in case the quick and easy solution is what you're looking for.

只需使用open() 打开文件,然后调用readlines() 方法.您将获得文件中所有字符串的列表.现在,您可以轻松地在最后一个元素之前添加字符串(只需在列表中最后一个元素之前添加一个元素).最后,您可以使用 writelines() 将这些写回文件.

Just open the file using open(), then call the readlines() method. What you'll get is a list of all the strings in the file. Now, you can easily add strings before the last element (just add to the list one element before the last). Finally, you can write these back to the file using writelines().

一个例子可能会有所帮助:

An example might help:

my_file = open(filename, "r")
lines_of_file = my_file.readlines()
lines_of_file.insert(-1, "This line is added one before the last line")
my_file.writelines(lines_of_file)

你不应该这样做的原因是,除非你做一些非常快速和肮脏的事情,否则你应该使用 XML 解析器.这是一个允许您使用 DOM、树和节点等概念智能地处理 XML 的库.这不仅是处理 XML 的正确方式,也是标准方式,使您的代码更易于移植,并且更易于其他程序员理解.

The reason you shouldn't be doing this is because, unless you are doing something very quick n' dirty, you should be using an XML parser. This is a library that allows you to work with XML intelligently, using concepts like DOM, trees, and nodes. This is not only the proper way to work with XML, it is also the standard way, making your code both more portable, and easier for other programmers to understand.

Tim 的回答提到检查 xml.dom.minidom 用于此目的,我认为这是一个好主意.

Tim's answer mentioned checking out xml.dom.minidom for this purpose, which I think would be a great idea.

这篇关于如何在 python 中更新/修改 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆