2

This should be extremely easy but I've now been at it an hour with no end in site. I'm using the simplekml module in python and I want to create a folder if one doesn't exists. I can't find anyway to check if a folder exists already without creating a for loop. I would think the below would work but of course it doesn't.

    kml = simplekml.Kml()
    testfold = kml.newfolder(name = 'testfolder')
    testfold2 = kml.newfolder(name = 'testfolder2')

    if 'testfolder' in kml.containers: 
        print True

The only thing that seems to return the fold names is:

for x in kml.containers:
    print x.name

But of course I would prefer not to iterate through every container in the kml file looking for a folder before then writing it if it isn't found. Please tell me there's a better way?!

CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
Jesse Reich
  • 87
  • 1
  • 1
  • 11

1 Answers1

1

That is because, kml.containers holds the list of objects of class simplekml.featgeom.Folder and name is an attribute of that class!

So when you check if 'testfolder' in kml.containers it returns false! You have to fetch the values in the name attribute of that container and then check if testfolder

>>> [each for each in kml.containers]
[<simplekml.featgeom.Folder object at 0x2ac156d8e910>, <simplekml.featgeom.Folder object at 0x2ac156d8e890>]
>>> [x.name for x in kml.containers]
['testfolder', 'testfolder2']
>>> True if 'testfolder' in [x.name for x in kml.containers] else False
True
Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23
  • Thanks Keerthana. One question, will this loop through all "points" as well? In other words, if every time I'm adding a point I have to loop through all points and folders to look for a folder, this could get very slow for adding a large number of points. – Jesse Reich Aug 08 '17 at 12:30
  • I get it. Definitely there will be an overhead if you loop through the kml.containers every time. I suggest to add the points to a list, and as and when you add a new point, append to that list. So while comparing you can make use of the updated list! – Keerthana Prabhakaran Aug 09 '17 at 05:35