Tuesday, March 2, 2021

PyQGIS - Add multiple shapefile vector layers to the QGIS project instance

 Sometimes, I need to load many shpafiles which are located in various folders into the QGIS project. A handy way to overcome this repetitive boring task is to use the PyQGIS script below.

import glob

# Use glob to recursively search all folders for .shp files...
shp_files = glob.glob(r'C:\Users\Yusuf_08039508010\Desktop\GIS Data\NGR\**\*.shp', recursive=True)
# print(shp_files)

layer_count = 0
for shp in shp_files:
    print("Loading...", shp)
    layer_name = shp.split('\\')[-1].split('.')[0]
    vlayer = QgsVectorLayer(shp, layer_name, "ogr")
    if not vlayer.isValid():
        print("Error: Layer Failed to Load!")
        layer_count += 1

print(f'Finished Loading total of: {layer_count} shapefiles.')

As seen below, I will have to open 11 folders and sun folders to load all the shapefiles into QGIS project. But with the script above, I just run once and all the shpafiles in both parent and child folders are loaded in few second.

Here the script loaded 66 shapefiles from all the directories as seen below.


No comments:

Post a Comment