I created memory files by chaining multiple processes (dissolve, multiparttosingleparts, pointsalonglines) and in the last step I add a new field to the memory layer.
My code looks this:
from qgis.core import *
import os
import processing
pathInput = "path/to/input/file.shp"
DISSOLVE
dissolve = processing.run("native:dissolve",{'INPUT':pathInput,
'FIELD':['highway', 'maxspeed', 'surface'],
'OUTPUT':'memory:'})
Get dissolve layer
dissolve_layer = dissolve['OUTPUT']
Create in-memory spatial index
QgsSpatialIndex(dissolve_layer.getFeatures())
MULTIPART TO SINGLEPARTS
multiparttosingleparts=processing.run("qgis:multiparttosingleparts",{'INPUT':dissolve_layer,
'OUTPUT':'memory:'})
layer_singleparts = multiparttosingleparts['OUTPUT']
Create in-memory spatial index
QgsSpatialIndex(layer_singleparts.getFeatures())
POINTS ALONG GEOMETRY
pointsAlongGeom=processing.run("native:pointsalonglines", {'INPUT':layer_singleparts,
'DISTANCE':10,
'START_OFFSET':5,
'END_OFFSET':5,
'OUTPUT':'memory:'})
layer_PntsAlngGeom = pointsAlongGeom['OUTPUT']
QgsSpatialIndex(layer_PntsAlngGeom.getFeatures())
ADD UNIQUE ID TO POINT MEMORY LAYER
layer_PntsAlngGeom.dataProvider().addAttributes([QgsField('point_id', QVariant.Int)])
layer_PntsAlngGeom.updateFields()
fld_idx = layer_PntsAlngGeom.fields().lookupField('point_id')
atts_map = {ft.id(): {fld_idx: ft.id()} for ft in layer_PntsAlngGeom.getFeatures()}
layer_PntsAlngGeom.dataProvider().changeAttributeValues(atts_map)
print('Done')
If I then add the in-memory layer to the map as a temporary layer like :
QgsProject.instance().addMapLayer(layer_PntsAlngGeom)
I can see, that everything worked correctly, so that there was an ID created but also that the CRS is correct.
So I assume, that the in-memory layer has all it needs to become a file. However, how can I now create a shapefile from it?
If this makes a difference: I do NOT want to make a file from the QgsMapLayer added to the map, but from the memory layer.
How can I do this? I couldn't find a section about in-memory layer in the PyQGIS Cookbook, therefore I hope to get some help here.
System Windows 10
QGIS 3.28 Firenze
pointsalonglinesalgorithm, instead of'OUTPUT':'memory'you can specify a path to where you want to save your shapefile. E.g.'OUTPUT':'C:/users/my_name/shapefiles/my_file.shp'. – Matt Apr 20 '23 at 14:19# ADD UNIQUE ID TO POINT MEMORY LAYERwill affect the file on disk, so theIDwill be added to the saved shapefile. – Matt Apr 20 '23 at 14:41$idand set your file destination as 'OUTPUT'. – Ben W Apr 20 '23 at 22:55