photo of person typing on computer keyboard

QGIS Python Tutorial – Working with Vector File

In my previous article, we learned how to add a vector layer to QGIS canvas using Python code. It’s pretty simple and straightforward. Now, we will continue working with the vector layer. We will perform some basic operations on the vector file such as counting the number of features and so on. In case you missed out, you can download the layer file that we will use in this tutorial using the link below.

Download Airport shapefile

Add Vector Layer to QGIS Canvas

We will briefly show you how to add the vector layer to the QGIS canvas. Open the Python window/console in your QGIS and then run this code. Don’t forget to change the file path with your own. The following code will load the ne_10m_airports.shp layer into QGIS.

#This is the variable for the shapefile location
AirportPath = "/Users/dhani/Documents/GIS Data/ne_10m_airports/ne_10m_airports.shp"

#Create a new variable and load the layer into QGIS canvas if TRUE. Otherwise, it will throw an error message
AirportLayer = QgsVectorLayer(AirportPath, "Airport", "ogr")
if not AirportLayer.isValid():
    print ("Cannot load layer")
else:
    QgsProject.instance().addMapLayer(AirportLayer)

Remove All Layers from QGIS Canvas

To remove all layers from QGIS using python code, we can do this code

MyProject = QgsProject.instance()
MyProject.clear()

#or you can also do this 
QgsProject.instance().clear()

Select all features in the active layer

To select all features in the active layer, we can use this code. Please note that this must be a vector layer.

#select all features in a vector layer
MyLayer = iface.activeLayer()
MyLayer.selectAll()

Count the features in a vector layer

Now we will count how many points in the Airport layer

MyLayer = iface.activeLayer()
print(MyLayer.featureCount())

Thanks for reading, we will continue the tutorial in the next article. Please stay tune and subscribe to this blog for more article like this.