I adapted Germán Carrillo's code to import xyz files (I use it to import river cross sections).
As the fields in my cross profile tables are separated by multiple spaces, what results in adding several empty columns if I use " " as decimal separator, I added a piece of code to replace the spaces by a comma (consecutive spaces are replaced by one coma). For the rest I used the same procedure as described in Germán Carrillo's post to import the cross profiles.
import os.path, glob
layers=[]
profile = 0
directory = 'X:/My/Working/Directory/' # Change this base path
for file in glob.glob(directory+'*.xyz'):
f = open(file, 'r')
lines = f.readlines()
f.close()
new_file = directory+'PT_'+str(profile+1)+'.xyz'
fw = open(new_file, 'w')
for l in lines:
fw.write(re.sub("\s+", ",", l.strip())+'\n')
fw.close()
uri = "file:///" + new_file + "?delimiter=%s&xField=%s&yField=%s&useHeader=no&crs=epsg:3943" % (",", "field_2","field_3")
vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
vlayer.setFieldAlias(0,'id')
vlayer.setFieldAlias(1,'X')
vlayer.setFieldAlias(2,'Y')
vlayer.setFieldAlias(3,'Y')
layers.append(vlayer)
profile +=1
QgsProject.instance().addMapLayers(layers)
As you can see in QGIS 3:
- addAttributeAlias has been replaced by setFieldAlias
- QgsMapLayerRegistry has been replaced by QgsProject
Below the original structure of my cross profiles:
1 1950459.685 2218176.491 37.574 0
2 1950468.259 2218173.250 37.466 0
3 1950471.806 2218171.910 37.466 0
4 1950474.013 2218171.076 35.000 0
5 1950477.754 2218169.662 35.000 0
6 1950480.095 2218168.777 36.465 0
7 1950483.372 2218167.539 36.465 0
8 1950495.173 2218163.079 37.214 0
And the resulting table after applying the strip function on each line.
1,1950459.685,2218176.491,37.574,0
2,1950468.259,2218173.250,37.466,0
3,1950471.806,2218171.910,37.466,0
4,1950474.013,2218171.076,35.000,0
5,1950477.754,2218169.662,35.000,0
6,1950480.095,2218168.777,36.465,0
7,1950483.372,2218167.539,36.465,0
8,1950495.173,2218163.079,37.214,0
There are probably some improvements that can be done, but at least it works for me.