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"

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Sep 26, 2022 at 18:41
2
  • can you upload a sample dataset to pastebin? Commented Sep 26, 2022 at 18:51
  • Here it is: pastebin.com/CKWikxrR Commented Sep 26, 2022 at 20:43

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)
answered Sep 27, 2022 at 6:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.