Get started with PyQGIS 02 - Manage layers with QGIS python console
Tags: qgis, python, pyqgis
Published: 2023-10-25 12:08:54

The [first chapter](https://dev.to/mierune/get-started-with-pyqgis-some-basic-commands-with-qgis-python-console-3he5) of this PyQGIS tutorial series told about basic commands and approach of PyQGIS module.
This second chapter tell you about how to manage layers with some usual commands.
You can use your own data or use a sample data of Paris region cities from [France government platform](https://www.data.gouv.fr/fr/datasets/r/5cd27d86-4859-40dc-b029-a215219eedf9).

## 1. Open script editor of Python Console 
In Python console we can launch commands one by one, but we need several commands to manage layers.
To run those at once, we need to open the script editor.

### 1.1. Open Python console in QGIS
As for the first chapter :
Open QGIS, menu -> Plugins -> Python Console
![Python console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8bbeipl8but0ghdhg5v.png)
Or use shortcut `Ctrl+Alt+P` (Windows) `command+option+P` (mac)

Python console open usually at the bottom of QGIS frame

![Python console on QGIS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/em395ftw347mv0beul3n.png)

### 1.2. Open Script Editor
Click on the `Show Editor` button to open script editor as below:

![Editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqo0gbrsrfqkg1jqbra8.png)



## 2. Layer related commands
Here are some basic commands to manage layers in a QGIS project.
### 2.1. Import layer from file
Layer can be load in QGIS with two commands:

```python
# 1- declare a new layer and specify file_path and layer name
layer = QgsVectorLayer(file_path, layer_name, "ogr")
# 2- import declared layer 
QgsProject.instance().addMapLayer(layer)
```

On script editor, copy the following code, adapt to the file you want to import, and run. 
```python
file_path = "your/path/data/target_file.shp"
layer_name = "my fantastic layer"

# declare a new layer and specify file_path and layer name
layer = QgsVectorLayer(file_path, layer_name, "ogr")
# import declared layer 
QgsProject.instance().addMapLayer(layer)
```

![Import layer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s57duq8aoye3v5scojqh.png)



### 2.2. Import only a part of features from file 
 
We can import a part of features by filtering declared layer.
The following command will filter data where 
`target_field = 'target_value'` 
and it should be put before import command.

```python
layer.setSubsetString("target_field='target_value'")
```

In process, layer name will be added with 'filtered' suffix: 
```python
file_path = "your/path/data/target_file.shp"
layer_name = "my fantastic layer filtered"

# declare a new layer and specify file_path and layer name
layer = QgsVectorLayer(file_path, layer_name, "ogr")
# filter layer before import
layer.setSubsetString("target_field='target_value'")
# import declared layer 
QgsProject.instance().addMapLayer(layer)
```

On below pic, data is filtered with only Paris' wards with:
```python
layer.setSubsetString("numdep=75")
```


![Paris](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/66f52fihe0tcj1ayulvf.png)



### 2.3. List layers
There are various ways to list layers: we can retrieve layers  as object or just layers name.

- Running following command directly on python console will show a list of layer, not by layer name, but by object showing layer ID, and their PyQgis type:
```python
QgsProject.instance().mapLayers()
```

![map layers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58txmk5l8uexwp1jnoip.png)

- Adding `.values` on above result will reduce response to class and layer name:
```python
QgsProject.instance().mapLayers().values()
```

![values layer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jyrw44cfy8zakepsgf22.png)



To retrieve only layers' name, use the `.name()` attribute of each layer object:
```python
for layer in QgsProject.instance().mapLayers().values():
     print(layer.name())
```

![list name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j57jig61q4v0bq0mqg0s.png)


### 2.3. Retrieve a layer by name
A layer can be retrieved by name with the following command:
```python
QgsProject.instance().mapLayersByName("search_layer_name")
```

This is the main way to retrieve a layer and manipulate it.
This command will not return layer, but a list of layers which fit to target name.


![retrieve layer by name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dq1ipsmisjb72zjvoqb.png)

So, to get layer as unique, you can add  an iteration like `[0]`, which means the first matching of returned list:
```python
QgsProject.instance().mapLayersByName("search_layer_name")[0]
```


### 2.4. Remove layer
`removeLayer method` of `QgsProject.instance()` is used. 
As written in [documentation](https://qgis.org/pyqgis/3.22/core/QgsProject.html#qgis.core.QgsProject.removeMapLayer), target layer ID is required.

layer ID can be retrieved with by adding `.id()` method of layer class that we retrieved in previous step.
```python
layer = QgsProject.instance().mapLayersByName("search_layer_name")[0]
print(layer.id())
```


![Layer id](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/we348jyecvq6zg99wn7x.png)


Thus, we can use this id to remove layer.
```python
layer = QgsProject.instance().mapLayersByName("search_layer_name")[0]
QgsProject.instance().removeMapLayer(layer.id())
```


![layer removed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7w032dg5nuqctjnf9er1.png)





## 3. The use of QgsProject class to manage layers

In this second chapter, `QgsProject.instance()` has been mainly used to add, retrieve and remove layer.
Regarding [documentation](https://qgis.org/pyqgis/3.22/core/QgsProject.html), many other manipulations can be done, such as remove all layers or manipulate other project matters.

Retrieving layers as objects also makes introduced us to  `QgsVectorLayer` which will be the topic of the next chapter.