1

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()
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
Schack
  • 833
  • 2
  • 7
  • 18
  • Hello. I doesn't know `kml` nor ``pykml`` but I'm interested to know: are the KML directories and files different from "normal" dirs and files created by common functions in Python ? What do they have special ? – eyquem Dec 12 '13 at 23:32

1 Answers1

1

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!"
Schack
  • 833
  • 2
  • 7
  • 18