1

I'm approaching now for the first time to Python console and I wanted to know step by step how to export in .csv two fields from the attribute table of a vector shapefile(.shp) using just PyQgis. Let's say that up to now I have edited as follows:

fn = "file path"
vlayer = iface.addVectorLayer(fn, "file path", "ogr")
features = vlayer.getFeatures()
for feature in features:
    print (feature [field], feature [2])

layer = QgsVectorLayer(fn, "ogr")
QgsVectorFileWriter.writeAsVectorFormat (layer, r "C: / path of file / filename_csv", "utf-8", None, "CSV", layerOptions = ['GEOMETRY = AS_XYZ']))

From this I get a .csv file but empty, how should I proceed?

1

I think this is the minimum required to export a shapefile to csv format:

file_path = "path/to/input.shp"
layer = QgsVectorLayer(file_path, "any_name", "ogr")
QgsVectorFileWriter.writeAsVectorFormat(layer, "path/to/output.csv", "utf-8", None, "CSV", layerOptions = ['GEOMETRY=AS_XYZ'])

Notice that for the layerOptions, there should not be any spaces inside the string:

E.g.

layerOptions = ['GEOMETRY = AS_XYZ']

Should instead be written as:

layerOptions = ['GEOMETRY=AS_XYZ']

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.