我一直在使用python的xml.etree.ElementTree库一点点,主要是玩弄它。然而,我注意到,python似乎将文件加载到内存中并在那里编辑它,然后刷新它,并继续使用未编辑的版本。例如,如果我的程序将一个元素添加到XML文件中,然后遍历该XML文件,它将不会看到它之前添加的内容。刷新Python的ElementTree中的文件
这里是我的代码的精简版本:
添加到文件:
import xml.etree.ElementTree as ET
tree = et.parse("file.xml")
root = tree.getroot()
newel = ET.Element("element", tag=foo,)
newel.text = bar
root.append(newel)
tree.write("file.xml")
for child in root:
if child.get("tag") == foo:
print(child.text)
难道我做错了什么,或者什么是“清新”的一个很好的方式,可以这么说,在XML文件在程序中,所以当我用for循环遍历程序时,我可以看到我的新元素?
我正在使用python 3.5。
我已经看到[这](HTTP:/ /stackoverflow.com/questions/27829575/python-refresh-file-from-disk),但它似乎并不适用。 – prongs95