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

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

问题描述

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



我考虑过以a(追加)模式打开XML文件。问题是新数据将在根关闭标记之后写入。



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



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



感谢您的时间。

解决方案

快速简便的方法,你肯定不应该(见下文),是使用readlines()将整个文件读入一个字符串列表。我写这个是为了快速简便的解决方案是你正在寻找的。

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



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

  my_file = open(filename,r)
lines_of_file = my_file.readlines()
lines_of_file.insert(-1,此行在最后一行之前添加line)
my_file.writelines(lines_of_file)

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



蒂姆的答案提到检查 http://docs.python.org/library/xml.dom.minidom.html 为此目的,我认为这是一个好主意。


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

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..

Thanks for your time.

解决方案

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.

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)

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 parses. 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's answer mentioned checking out http://docs.python.org/library/xml.dom.minidom.html for this purpose, which I think would be a great idea.

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

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