Sunday, April 28, 2024

PyQGIS Count Features in Layers

 I was working with hundreds of layers from OSM .pbf files. A .pbf file can contain multiple layers inside it, whenever I load one .pbf file, I get like 4 to 5 layers. By the time I load 50 of .pbf files, you know approximately how many layer I got to work on.

Since, there are much layers to handle manually I had to write script to automate some of my workflows.

1) Get layer path on disc and count number of feature in it

# Get path to layer location on disc...
layers_on_panel = QgsProject.instance().mapLayers()
layer_paths = [l.source() for l in layers_on_panel.values()]

# Count Features in layer...
for lpath in layer_paths:
    if 'power_substation_point' in lpath:
        # Read the vector layer...
        layer = QgsVectorLayer(lpath, '', 'ogr')
        # Count the features...
        print( layer.featureCount() )



2) Load .pbf layer to 'layer panel' from path

## Load layer from path...
for lpath in layer_paths: # Note that 'layer_paths' is from above...
    if 'water_pipeline' in lpath:
        pbf_file_name = lpath.split('\\')[-1].split('.')[0]
        
        # Construct file name...
        fn1 = lpath.split('\\')[-1].split('.')[0]
        fn2 = lpath.split('\\')[-1].split('.')[-1].split('=')[-1]
        display_name = fn1 +'__'+ fn2
        
        # Read vector file and add it layer panel...
        layer = QgsVectorLayer(lpath, display_name, 'ogr')
        QgsProject.instance().addMapLayer(layer)
        
print('\nDone...')


3) Write layer paths to text file

with open('test.txt', 'w') as f:
    for a in layer_paths: # note 'layer_paths' is from above...
        e = str(a) + '\n'
        f.write(e)
        
print('Done...')



That is it!

No comments:

Post a Comment