0

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"

2

1 Answer 1

2

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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