How to create multiple QGIS layers from multiple text files?

Assuming all your text files are into the same directory, you can run this code snippet in the QGIS Python console to get your files loaded as individual layers in QGIS:

import os.path, glob
layers=[]
for file in glob.glob('/tmp/xy/*.txt'): # Change this base path
  uri = "file:///" + file + "?delimiter=%s&xField=%s&yField=%s&useHeader=no&crs=epsg:3116" % (";", "field_1","field_2")
  vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
  vlayer.addAttributeAlias(0,'X')
  vlayer.addAttributeAlias(1,'Y')
  vlayer.addAttributeAlias(2,'Z')
  vlayer.addAttributeAlias(3,'classification')
  layers.append(vlayer)

QgsMapLayerRegistry.instance().addMapLayers(layers)

As you see, it works for GNU/Linux paths, I don't know how the uri (specifically the file path) should look like for Windows. Also, adjust the crs for your own case.

I also wanted to tell you how to change field names automatically, but it seems that delimited-text based layers cannot be edited. I guess the most you can do is to assign aliases for your columns, as the code does.


Combine all text files in a windows directory with the copy command:

copy *.txt river.txt

On Linux use the cat (concatenate) command:

cat * > river.txt

Then in QGIS for the merged text file use 'Add Delimited Text Layer' button.


The answer from @GermanCarrillo worked for me and saved much time.

With a text file structured like so: Time[s],Easting[m],Northing[m],Height[m],Roll[deg],Pitch[deg],Yaw[deg] 170258.002391,332731.5085,5794908.7794,46.1642,0.409501631306,-5.248541020385,0.684043081908

The code that worked for me in windows is:

import os.path, glob
layers=[]
for file in glob.glob('C:/Projects/2829/locations/20160524/*.txt'): # Change this base path
  uri = "file:///" + file + "?delimiter=%s&xField=%s&yField=%s&useHeader=no&crs=epsg:28355" % (",", "field_2","field_3")
  vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
  vlayer.addAttributeAlias(1,'X')
  vlayer.addAttributeAlias(2,'Y')
  layers.append(vlayer)

QgsMapLayerRegistry.instance().addMapLayers(layers)