Friday, 27 July 2018

python - Create a script to add delimited text layer in QGIS


I'm trying to use QgsVectorLayer() function to add delimited text layer in QGIS. So I have a txt file (T_1999_1_2.txt) in path: "D:\PATRICIA\DOCUMENTOS\ESTACOES METEOROLOGICAS\DADOS METEOROLOGICOS\T" and I want to create a shapefile named: T_1999_1_2.shp. The txt file structure is:



par;num;ano;mes;dia;D;btq 3;705;1999;1;2;-999,9;S;40,43885833;-8,43994167
3;619;1999;1;2;25,0;A;41,70972;-8,02699 3;718;1999;1;2;104,0;A;39,78055278;-8,82096667 3;766;1999;1;2;28,0;A;38,76620278;-9,12749444 3;560;1999;1;2;333,0;A;40,71492778;-7,89591667 3;669;1999;1;2;-999,9;S;39,83950000;-7,47866944 3;848;1999;1;2;-999,9;S;38,48486667;-7,47291667 3;555;1999;1;2;8,0;A;41,70655556;-8,80210833



I have tried to run the script but appears the same window error ("Error in file. File cannot be opened or delimiter parameters are not valid") My sript is the following one:


uri = "D:\PATRICIA\DOCUMENTOS\ESTACOES METEOROLOGICAS\DADOS METEOROLOGICOS\T\T_1999_1_2.txt?delimiter=%s&xField=%s&yField=%s" % (";", "x", "y") 

vlayer = QgsVectorLayer(uri, "D:\PATRICIA\IG\QGIS\FWI\T\T_1999_1_2.shp", "delimitedtext")

I don't understand, why it doesn't work.



Answer



Change variables indir and outdir according to your need. The code will find each file with extension 'txt' in indir and every subdirectory of indir. If you need another coordinate system than EPSG 4326, please change the EPSG number in line 9. The converted files will be written to directory outdir.


import os
indir = 'G:/LANUV'
outdir = 'G:/LANUV'
for root, dirs, files in os.walk(indir):
for file in files:

if file.endswith('.txt'):
fullname = os.path.join(root, file).replace('\\', '/')
filename = os.path.splitext(os.path.basename(fullname))[0]
uri = 'file:///%s?crs=%s&delimiter=%s&xField=%s&yField=%s&decimal=%s' % (fullname, 'EPSG:4326', ';', 'x', 'y', ',')
layer = QgsVectorLayer(uri, 'my_layer', 'delimitedtext')
QgsVectorFileWriter.writeAsVectorFormat(layer, outdir + '/' + filename + '.shp', 'CP1250', None, 'ESRI Shapefile')

Copy the code and paste it into the Python console.


This code fragment uses code from this thread.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...