I'm using QGIS v3.26, and cannot seem to get code referenced from another Q&A to work. This is the previous Q&A on this topic that I was looking at: How to create multiple QGIS layers from multiple text files?
The files I'm attempting to import are from the EDGAR database showing spatial emission measurements in .txt files. They have three headers; when I manually import a layer using the gui in QGIS I have to select "Number of header lines to discard: 2" under the Record and Field Options tab. The third header has the column names.
import os.path, glob
from qgis.core import QgsProject, QgsVectorLayer
layers=[]
for file in glob.glob('/home/Documents/*.txt'): # Change this base path
uri = "file:///" + file + "?delimiter=%s&xField=%s&yField=%s&useHeader=yes&crs=epsg:4326" % (";", "lat","lon")
vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
vlayer.setFieldAlias(0,'Y')
vlayer.setFieldAlias(1,'X')
layers.append(vlayer)
QgsProject.instance().addMapLayers(layers)
If I run this code all I get is "SyntaxError: invalid syntax"
-
can you upload a sample dataset to pastebin?Bernd Loigge– Bernd Loigge2022年09月26日 18:51:10 +00:00Commented Sep 26, 2022 at 18:51
-
Here it is: pastebin.com/CKWikxrRdigital-consolation– digital-consolation2022年09月26日 20:43:41 +00:00Commented Sep 26, 2022 at 20:43
1 Answer 1
You are missing skipLines=2
. The most easy way to find out how the uri
should look like is to load one example manually and than look into the Information
section of the loaded layer. There you will find the Source
with all the parameters you need.
This worked for me:
import os.path, glob
from qgis.core import QgsProject, QgsVectorLayer
layers=[]
for file in glob.glob(r'/tmp/*.txt'): # Change this base path
uri = "file:///" + file + "?type=csv&delimiter=;&skipLines=2&detectTypes=yes&xField=lon&yField=lat&crs=EPSG:4326&spatialIndex=no&subsetIndex=no"
vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
vlayer.setFieldAlias(0,'Y')
vlayer.setFieldAlias(1,'X')
layers.append(vlayer)
QgsProject.instance().addMapLayers(layers)
Explore related questions
See similar questions with these tags.