Add a line to a file if it not exist using python

前端 未结 2 1460
悲&欢浪女
悲&欢浪女 2021-01-29 13:19

I have an xml file as follows:


  

        
2条回答
  •  伪装坚强ぢ
    2021-01-29 13:56

    Your question is based on lines in text files, but the input file is clearly XML, so assuming you actually want to add an Import if it doesn't exist, try this:

    import xml.dom.minidom
    
    importstring = "$(Projectname).targets"
    filename = "test.xml"
    
    tree = xml.dom.minidom.parse(filename)
    Project = tree.getElementsByTagName("Project")[0]
    
    for Import in Project.getElementsByTagName("Import"):
        if Import.getAttribute("Project") == importstring:
            break
    else: # note this is else belongs to the for, not the if
        newImport = xml.dom.minidom.Element("Import")
        newImport.setAttribute("Project", importstring)
        Project.appendChild(newImport)
    
    tree.writexml(open(filename, 'w'))
    

提交回复
热议问题