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

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

问题描述

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

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

我考虑过以"a"(附加)模式打开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.

蒂姆的答案提到要为此检查 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天全站免登陆