I'm new to QGIS(3.20.2), and have even less experience with python. I've been working on automating a simple task and have been having difficulty tying together the pieces of information that I've found on the forum. What I'm looking to do is create a standalone script that runs without opening QGIS, takes all the text files from a specified folder, and creates output polygon files from each of these text files and places them in another specified folder. So far, I've mostly been able to accomplish this task within the python console of QGIS, but am having trouble looping the processing algorithms so they run on all the files in a folder, and running this script outside of QGIS. My script so far does the following:
- Creates delimited text layers from all the text files in a folder and adds them to the map. The text file format is shown below:
ID | X | Y | Sort |
---|---|---|---|
1 | -77.1 | 36.4 | 1 |
2 | -77.1 | 36.3 | 1 |
3 | -77.09 | 36.2 | 2 |
4 | -77.09 | 36.3 | 2 |
- Runs the Point to Path algorithm on an individual input file using the start and end xy coordinates, which has field_4 (sort) as the path group expression.
- Runs the Polygonize algorithm on the input file from the previous step and exports it to a .kml file in a specified folder.
The code that I'm using to do this is as follows:
import os.path, glob
from qgis.core import QgsProject, QgsVectorLayer
layers=[]
for file in glob.glob('C:/Users/1134377/Documents/ASD/ModelBuilder/*.txt'): # Change this base path and change backslashes to forward slashes
uri = "file:///" + file + "?delimiter=%s&xField=%s&yField=%s&useHeader=no&crs=epsg:4326" % (",","field_2","field_3") #(Delimeter, XField, YField) #1st column in file is column 1
vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
vlayer.setFieldAlias(1,'X') #these order of columns go: 0, 1, 2 etc
vlayer.setFieldAlias(2,'Y')
layers.append(vlayer)
QgsProject.instance().addMapLayers(layers)
processing.runAndLoadResults("native:pointstopath", {'INPUT':'delimitedtext://file:///C:/Users/1134377/Documents/ASD/ModelBuilder\\*.txt?delimiter=,&xField=field_2&yField=field_3&useHeader=no&crs=epsg:4326','CLOSE_PATH':False,'ORDER_EXPRESSION':'','NATURAL_SORT':False,'GROUP_EXPRESSION':'\"field_4\"','OUTPUT':'C:/MyFolder/Path.shp'})
processing.runAndLoadResults("native:polygonize", {'INPUT':'C:/MyFolder/Path.shp','KEEP_FIELDS':False,'OUTPUT':'C:/Users/1134377/Documents/ASD/ModelBuilder/Outputs/Poly.kml'})
The limitation of this script is that it doesn't run the algorithms (point to path & polygonize) on all the text layers that are added to the map using the beginning portion of code. It also needs to be run within the python console within QGIS, and not as a standalone script.