0

Running a function in QGIS (example - "native:geometrysmooth") on a single shapefile, I can copy the 'Python Command' once setup and replicate this to run in the Python Console for a single run.

If I run this code with variations for multiple shapefiles (have hundreds with different names), the processing only generates for the last entry (processing.run) (i.e only one is generates).

Is there a simple way to batch these out, currently with hard link input and output folders (to C drive)?

Note: I have been able to rename each code string input and output to the corresponding shapefile.

Example (copy and paste all together and try to run as together, as copying and pasting each is extremely inefficient).

processing.run("native:smoothgeometry", {'INPUT':'C:\\_Work\\QGIS_Learning\\1_Batch_Exports\\5_Polylines\\1_Original\\1_Polyline_1.shp','ITERATIONS':2,'OFFSET':0.25,'MAX_ANGLE':180,'OUTPUT':'C:\\_Work\\QGIS_Learning\\1_Maps_Exports\\5_Polylines\\2_Simplified\\2_Polyline_1_Simplified.shp'})

processing.run("native:smoothgeometry", {'INPUT':'C:\\_Work\\QGIS_Learning\\1_Batch_Exports\\5_Polylines\\1_Original\\1_Polyline_7.shp','ITERATIONS':2,'OFFSET':0.25,'MAX_ANGLE':180,'OUTPUT':'C:\\_Work\\QGIS_Learning\\1_Maps_Exports\\5_Polylines\\2_Simplified\\2_Polyline_7_Simplified.shp'})

etc.

0

1 Answer 1

2

You can use the os module to find all shapefiles in a folder (including all subfolders), then process each with a for loop:

import os
input_folder = r"C:\_Work\QGIS_Learning\1_Batch_Exports\5_Polylines\1_Original"
output_folder = r"C:\_Work\QGIS_Learning\1_Maps_Exports\5_Polylines\2_Simplified"

#Create a list of all shapefiles in input_folder
shapefiles = []
for root, folder, files in os.walk(input_folder):
    for file in files:
        if file.endswith(".shp"): #If the file is a shapefile. You might want to add more conditions like: and "polyline" in file.lower(), etc.
            fullname = os.path.join(root, file) #Combine input folder with filename to a full path
            shapefiles.append(fullname) #Append it to the list

#Process each shapefile in the list
for shapefile in shapefiles:
    out_name = os.path.basename(shapefile).replace(".shp", "_Simplified.shp") #Create the output filename
    out_file = os.path.join(output_folder, out_name) #Create the full path
    processing.run("native:smoothgeometry", 
        {'INPUT':shapefile,'ITERATIONS':2,'OFFSET':0.25,'MAX_ANGLE':180,
        'OUTPUT':out_file})

Take a look at: Python String Methods and os.path

If you have multiple processing steps and dont want to save each steps result you can chain them.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.