Get started with PyQGIS 03 - Manipulate vector layers with QGIS python console
Tags: qgis, python, pyqgis
Published: 2024-01-31 10:17:52

[On the previous chapter](https://dev.to/mierune/get-started-with-pyqgis-02-manage-layers-with-qgis-python-console-mhc), we get started with vector layer classes called `QgsVectorLayer`.


It could be set as follow:
```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)
```

and layer name can be retrieved as follow :
```python
# each layer is a QgsVectorLayer object
for layer in QgsProject.instance().mapLayers().values():
     print(layer.name())
```

Regarding [documentation](https://qgis.org/pyqgis/master/core/QgsVectorLayer.html), `QgsVectorLayer` class is full of functions. Let check some basic functions with QGIS python console!


## 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. Vector Layer related commands
Import the vector layer you want, here is Japan Prefectures


![Japan prefectures layer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u2m326w91pyd1ryn6vi2.png)

### 2.1. Retrieve target layer by name
As last chapter, we will retrieve layer by name (here `japan_pref` ), by
```python
layer = QgsProject.instance().mapLayersByName("japan_pref")[0]

# check
print(layer)
```

Result : 
```python
<QgsVectorLayer: 'japan_pref' (ogr)>
```

### 2.2. Retrieve layer extent
Simply add 
```python
layer_extent = layer.extent()
print("extent: ", layer_extent)
```

The result should be a `QgsRectangle` object.
```python
extent: <QgsRectangle: 122.93372516199046629 24.04561582899132333, 148.89439264601270452 45.55724341400912891>
```

Coordinates looks to be in geographic system, let's check.

### 2.3. Retrieve layer extent
Simply write 
```python
layer_crs = layer.sourceCrs()
print("CRS: ", layer_crs)
```

The result should be the WGS 84 (EPSG:4326) reference system.
```python
CRS: <QgsCoordinateReferenceSystem: EPSG:4326>
```


![layer crs and extent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/doa0d4cx2tx5appsfj4d.png)

### 2.4. Retrieve the number of features of the target layer
`featureCount()` method can do it.
you can combine with `name()` method to write a clean message 
```python
msg = f"{layer.name()} layer has {layer.featureCount()} features."
print(msg)
```

And here is the number of Japan prefectures:
```python
japan_pref layer has 47 features.
```

### 2.5. Retrieves vector layer fields
You can try 
```python
layer_fields = layer.fields()
print (layer_fields)
```

Result is an unreadable code, BUT!
class name `QgsFields` makes us to find a way to solve it.
```python
<qgis._core.QgsFields object at 0x0000024950231160>
```

Let's check documentation. 
You can check by searching _QgsFields_ with your favourite search engine.
Regarding, [Qgs Fields Documentation ](https://qgis.org/pyqgis/3.0/core/other/QgsFields.html) `names` method may be fine.

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

Let's try!

```python
layer_fields = layer.fields()
print (layer_fields.names())
```

I got it !
![layer fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/viktqfn5219jbzplmjpy.png)

## 3. Check output PyQgis class and its methods, a good pratice to make you grow up in PyQGIS
In this chapter, `QgsVectorLayer` basic methods has been used, and regarding documentation, many other usages can be done.

The last method to retrieve field is a combination of `QgsVectorLayer` and `QgsFields`.
However, we saw that when we hit to an unknown class, we can still moving on by checking documentation of this class, and find the good method easily.

This is a good way to understand easily a huge library such as PyQGIS.