2

I'm writing a standalone script for QGIS. In this script I want to import a couple of text files saved as .xyz. When I import them in QGIS I have to use "Import layers as delimited text", thus they are not rasters. They are text files with lots of rows and each row contains x,y and z coordinates.

After I import them I want to check a condition and export them to a new folder. The import part works fine but I get no export files in my output folder. That's the export part of the script:

lyr = QgsVectorLayer(uri, name, "delimitedtext")
outDir = 'C:/Users/user/Desktop/output'
fields = lyr.fields()
QgsVectorFileWriter.writeAsVectorFormat(lyr, outDir, "utf-8", fields, "CSV",
                                        layerOptions=['GEOMETRY=AS_XYZ'])

When I try to run the script, I don't get an error message but there are also no files in my output folder. I don't see the error. Can someone help me?

I'm using QGIS 3.4.13

EDIT

I checked the answers and modified the code but it is still not working. Still no error message and still no files in my output folder.

This is the whole function without the condition:

def moveFiles(self):
    inputDir = self.dlg.input_folder.text() #directory of xyz files - "Users/denni/Desktop/xyz_data"
    outDir = self.dlg.output_folder.text()  #output directory - "C:/Users/denni/Desktop/output/"
    crs = "EPSG:25832"

    for file in glob.glob("*.xyz"):
        uri = "file:///" + inputDir +"/"+ file + "?type=csv&delimiter=%s&crs=%s&xField=%s&yField=%s" % (" ", crs, "field_1", "field_2")
        name = file.replace('.xyz', '')
        lyr = QgsVectorLayer(uri, name, "delimitedtext")
        outputPath = outDir + file
        QgsVectorFileWriter.writeAsVectorFormat(lyr, outputPath, 'utf-8', lyr.crs(), "CSV",
                                                layerOptions='GEOMETRY=AS_XYZ')

What could be the problem?

3

There are various issues here. A correction below (tested before answering)

import os
from urllib.parse import urlparse

# URI should contain the path from your existing file not where you want to write
# Your extension must be csv (ps: tested with xyz extension and fails later)
uri = 'file:///home/thomasg/csv-pyqgis/points_xyz.csv?type=csv&detectTypes=yes&xField=x&yField=y&zField=z&crs=EPSG:4326&spatialIndex=yes&subsetIndex=no&watchFile=no'

lyr = QgsVectorLayer(uri, 'myname', "delimitedtext")
filename = urlparse(uri).path.split(os.path.sep)[-1].replace('.xyz', '.csv')
outDir = '/tmp/output'
# Create dir if not present
if not os.path.isdir(outDir):
    os.mkdir(outDir)

# Change arguments to match allowed signature of the function
# output path changed by concatenating directory output and file
# This path is where you want to write content
outfilepath = os.path.join(outDir, filename)
QgsVectorFileWriter.writeAsVectorFormat(lyr, outfilepath, 'utf-8', lyr.crs(), "CSV", layerOptions=['GEOMETRY=AS_XYZ'])
5
  • Hmm to replace the "xyz" with "CSV" didn't work either. I edited my question to explain my intend.
    – DGIS
    Feb 10 '20 at 16:35
  • Your code works for you? Still nothing is written in my output directory and still no error message... I guess I will go through the code again on a fresh day. Thanks so far
    – DGIS
    Feb 10 '20 at 18:51
  • Added the if block not os.path.isdir and done a mistake while copying... Tested again and works
    – ThomasG77
    Feb 10 '20 at 21:17
  • Hello Thomas, I tried your code but it still didn't work. After, I removed again the parts that didn't seem necessary (is the if block really necessary?) and now edited my question and uploaded the whole function. Any ideas where the error could be?
    – DGIS
    Feb 26 '20 at 18:03
  • Made again a correction due to extension (it must be csv from another test) You can download my sample file gist.githubusercontent.com/ThomasG77/… Can't help more
    – ThomasG77
    Feb 26 '20 at 23:00
2

writeAsVectorFormat method has three different usages. Your code match none of them. The code is correct syntactically, but incorrect logically. Your code matchs QgsVectorFileWriter constructor method.

lyr = QgsVectorLayer(uri, name, "delimitedtext")

outFilePath = 'C:/Users/user/Desktop/output/filename.csv'

QgsVectorFileWriter.writeAsVectorFormat(lyr,
                                        outFilePath,
                                        "utf-8",
                                        driverName="CSV",
                                        layerOptions=['GEOMETRY=AS_XYZ'])

Then change filename.csv into filename.xyz.

2
  • It will not work. Second arg is a file path not a directory path. The code will write C:/Users/user/Desktop/output.csv (tested while answering :) )
    – ThomasG77
    Feb 10 '20 at 17:29
  • csv Extension is added automatically. Feb 10 '20 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.