QGIS – How to Create Multiple QGIS Layers from Multiple Text Files

batchlayerspyqgisqgistext;

I have a few hundred txt files (each representing a line of a river bed profile) that I need to load as (point-) layers in QGIS. Partial example:

4504764.8331;5374251.3024;397.8871;2
4504764.7761;5374250.8056;397.8555;2
4504764.7191;5374250.3089;397.8295;2
4504764.6621;5374249.8121;397.8149;2
4504764.6051;5374249.3154;397.7977;2
4504764.5481;5374248.8186;397.7725;2

It works manually (layer -> add delimited text layer, then renaming the columns after import) but given the volume I can't do it all by hand.

I found a similar two year old question here: How to import multiple textfiles in one step , but "create a plain text file called .vrt file for each of csv files" doesn't sound so peachy. The files are also missing the header line, but I know the format: "X; Y; Z; classification".

Is there any way to do this without having to code up a text generator for those vrt files and inserting header lines into all csvs?

Best Answer

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.

Related Question