Python:编写xml文件时丢失内容

Python:编写xml文件时丢失内容,python,xml,lxml,minidom,Python,Xml,Lxml,Minidom,我正在使用python3.5和lxml(有时还有minidom)来编写和读取xml文件 我有多个进程来读写同一个xml文件,有时文件完全是空的。当我手动关闭一个进程时,就会发生这种情况 这是修改xml的函数示例: from lxml import etree as le file = open("generalList.xml", 'r') tree = le.parse(file) file.close() for bad in tree.xpath("//unit"): ip = ba

我正在使用python3.5和lxml(有时还有minidom)来编写和读取xml文件

我有多个进程来读写同一个xml文件,有时文件完全是空的。当我手动关闭一个进程时,就会发生这种情况

这是修改xml的函数示例:

from lxml import etree as le
file = open("generalList.xml", 'r')
tree = le.parse(file)
file.close()
for bad in tree.xpath("//unit"):
   ip = bad[0].text
   if ip == data[1]:
      bad.getparent().remove(bad)
file = open("generalList.xml", 'wb')
tree.writexml(file)
file.close()

有没有办法避免这个问题

您的示例可能不完整,但看起来您混合了minidom和lxml方法来编写文件,这可能会生成一个空白文件,尤其是在您的示例中

检查是否正在对lxml
对象使用
write()
方法 和
writexml()
用于minidom对象

编辑:

要了解可能发生的情况:

file = open("versions.xml", 'wb')  # file is blank

import time  # add this to take a moment to check the blank file in your folder
time.sleep(60)

# here,  if shit happens, you lose everything

tree.write(file) # then the file is written and I/O closed
file.close()

您可以添加一些try/except语句,以避免代码中的bug产生这种效果,但是如果您在编写=>空白文件时中断了该过程,则非常感谢!明天早上我会尝试,我会让你知道有一个函数,我使用了lsml和minidom write函数,谢谢!但是,如果我在编写xml的过程中切断电源,可能会丢失文件吗?@G.Threepwood,我编辑答案来解释杀死过程的危险