pythongeocodingkmlpykml

Appending an empty folder to an existing folder in a KML file using Python


I've been trying to figure this out on my own but I'm stuck. I want to add an empty folder to an existing folder in an existing KML file. This is what I have so far, when I open the file, there's no new folder named "test".

import pykml
from pykml.factory import KML_ElementMaker as KML
from pykml import parser

x = KML.Folder(KML.name("test"))

with open("Scratch Paper.kml") as f:
    doc = parser.parse(f).getroot()
    a = doc.Document.Folder.Folder[0]
    a.append(x)
f.close()

Solution

  • So, it turned out to be much easier than I thought... I'm still trying to learn good practice, but opening the file in read mode, copying the data I want, and then re-opening in write mode seems to accomplish what I want.

    If others out there see a better way to do this, please let me know! Thanks!

    import lxml
    from lxml import etree
    import pykml
    from pykml.factory import KML_ElementMaker as KML
    from pykml import parser
    
    x = KML.Folder(KML.name("meow"))
    
    with open("Scratch Paper.kml", "r+") as f:
        doc = parser.parse(f).getroot()
        print doc.Document.Folder.Folder[3].name
        a = doc.Document.Folder[0]
        a.append(x)
        finished = (etree.tostring(doc, pretty_print=True))
    
    with open("Scratch Paper.kml", "w+") as f:
        f.write(finished)
    
    print "Done!"