【问题标题】:Python: Losing content while writing an xml filePython:在编写 xml 文件时丢失内容
【发布时间】:2017-06-27 09:30:00
【问题描述】:

我正在使用 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()

有没有办法避免这个问题?

【问题讨论】:

    标签: python xml lxml minidom


    【解决方案1】:

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

    检查你是否对 lxml tree 对象使用 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 语句来避免代码中存在错误的这种影响,但如果您在编写过程中切断进程 => 空白文件

    【讨论】:

    • 非常感谢!明天早上我会试试,我会告诉你
    • 有一个函数是我用lsml和minidom write函数的,谢谢!但是,如果我在进程写入 xml 时切断电源,我可能会丢失文件吗?
    • @G.Threepwood,我编辑答案来解释杀戮过程的危险
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多