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

前端 未结 2 1461
悲&欢浪女
悲&欢浪女 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'))
    
    0 讨论(0)
  • 2021-01-29 14:13

    Take the XML parser of your choice, parse the file, manipulate the file using the related API, write it back.

    0 讨论(0)
提交回复
热议问题