Writing one WKT file per feature in QGIS

Someone in #qgis just asked about this so here is a minimal pyqgis (for QGIS 3) example how you can write a separate WKT file for each feature of the currently selected layer. Careful with too many features, filesystems do not like ten thousands of files in the same directory. I am writing them to /tmp/ with $fid.wkt as filename, adjust the path to your liking.

layer = iface.activeLayer()
features = layer.getFeatures()

for feature in features:
  geometry = feature.geometry()
  wkt = geometry.asWkt()
  
  fid = feature.attribute("fid")
  filename = "/tmp/{n}.wkt".format(n=fid)
  
  with open(filename, "w") as output:
    output.write(wkt)

One thought on “Writing one WKT file per feature in QGIS

  1. Torsten

    Thanks for your patient and advice.

    By your code I get a error message: FileNotFoundError: [Errno 2] No such file or directory: ‘C:/tmp/27.wkt’.

    The attribut “name” schould be part of the filename. As jef correctet the code it works:
    features = vlayer.getFeatures()

    for feature in features:
    name = feature.attribute(“name”)
    filename = ‘C:/temp/wkt/{x}.txt’.format(x=name)
    file = open(filename, “w”)
    file.write(feature.geometry().asWkt())
    file.close()

    Thanks a lot :)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.