TransWikia.com

Processing several KML files in different folders using QGIS

Geographic Information Systems Asked by SKiD on October 5, 2021

I currently search for a way to load different KML files into one project. The thing is, that there are several KML files in the folders, which need to be displayed on an OpenStreetMap layer. I have quite less experience using the Modeler or Python scripting and couldn’t find any tutorials.

The hierarchy of the folder is like this:

  main_folder
    --> subfolder_1
      --> subsubfolder_1
        --> KML-file ss1_a.kml
        --> KML-file ss1_b.kml
      --> subsubfolder_2
        --> KML-file ss2_a.kml
        --> KML-file ss2_b.kml
      --> KML-file s1_a.kml
      --> KML-file s2_b.kml
    --> subfolder_2
    --> subfolder_3

The folders do hold different amounts of files and each file inside of one folder needs to be visualized in the same file so that I have one result image for each folder. I only want to set the root folder (main_folder) and I want to process the files in each folder recursively.

I was trying to use the different modeler functions, but it is really complex and hard to understand. Could someone give me a hint, how to solve this problem? Is this may be easier to do in Python?

One Answer

Try using os.walk:

import os
root_folder = r'/home/bera/Downloads' #Change to match your main folder

for root,folders,files in os.walk(root_folder):
    for file in files:
        if file.endswith('.kml'):
            vl = QgsVectorLayer(os.path.join(root,file), os.path.splitext(file)[0]) #Create vector layer
            QgsProject.instance().addMapLayer(vl) #Add it to map

enter image description here

Correct answer by BERA on October 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP