1

I tried to import several text files using the Python console, but I failed.

This is the code I used:

import os.path, glob
layers=[]
for file in glob.glob('E:/tmp/QGIS_CSVimport_test/*'):
uri = "file:///" + file + "?type=csv&xField=x&yField=y&spatialIndex=no&subsetIndex=no&watchFile=no&crs=epsg:32156"
vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
vlayer.addAttributeAlias(0,'x')
vlayer.addAttributeAlias(1,'y')
layers.append(vlayer)

QgsMapLayerRegistry.instance().addMapLayers(layers)

example of one txt-file

0

1 Answer 1

3

Try this:

import glob, os

layers = []
for file in glob.glob(r'/home/bera/Desktop/GIStest/C*.csv'):
    print(file)
    uri = f"file://{file}?type=csv&xField=x&yField=y&zField=z&crs=EPSG:32156"
    vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
    vlayer.setFieldAlias(1,'XXX') #First (index 0) field is Nr, x is second
    vlayer.setFieldAlias(2,'YYY')
    layers.append(vlayer)

QgsProject.instance().addMapLayers(layers)

I usually add one csv manually Ctrl+Shift+T, go to layer properties, and copy the source string and use as uri template:

enter image description here

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.