0

I have a PostGIS-Table (PostGIS-layer) with more than 400 Polygons (ID, name, geom). I need the WKT of each feature in the layer saved in a "polygon_name".txt file with the name of the Polygon. How to solve that lovely by QGIS and pyQGIS or is there a direct way in postgis.

The result must be a folder with more than 400 *.txt files named by the names of the polygons.

After some help especialy by hannesW und jef I solved it in QGIS with pyqgis by the code:

    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()
  • 1
    For the people who vote this off-topic, could you please elaborate on it? When I read the keywords in the question like wkt, qgis, postgis, polygons, I really wonder why. – pLumo Jun 13 '18 at 10:21
  • 2
    @RoVo This question is asking for help coding Python (pyQGIS) or SQL, but it doesn't include any code or show what's already been attempted (if anything). This falls pretty cleanly into one of the off-topic close reasons. While your bash solution is quite nice, we have no way of knowing if the asker can even use it due to the lack of information. (Do they have bash? They could be using Windows. Maybe this needs to be included into a QGIS plugin, etc...) – Evil Genius Jun 13 '18 at 11:21
  • Thanks, I was just curious. But you're right, no coding attempt is indeed an issue. – pLumo Jun 13 '18 at 11:29
3

Bash solution:

while IFS= read -r row; do
    name=$(echo "$row" | cut -f1)
    echo "$row" | cut -f2 > "${name}.txt"
done < <(psql -d database -AtF $'\t' -c "select name,st_astext(geom) from table")

(Replace database and table to your needs)


Explanation:

Make a psql query (psql -d database -c) using tab as field delimiter -F $'\t' to easily extract the fields later with the cut tool. Remove formatting with -A (--no-align) and remove field names / header -t (--tuples-only).

Loop through each row of the result (while IFS= read -r row; do [...] done < <(psql [...])).

Inside the loop, extract name from the row: echo "$row" | cut -f1 (-f1 means first field). Then extract the wkt the same way (-f2) and send it to a file named > ${name}.txt.

  • It looks great, thanks. Thanks a lot for the explanation, I learned a lot. But I don't know where to execute it, in psql bash? There I get a syntax error at or near "name" name=$(echo ... – Torsten Jun 14 '18 at 8:12
  • You need to run this in a bash shell / terminal. If you have windows, you can possibly install WSL, but I use Linux, so I cannot help you with this. But you could make a similar script with e.g. Python... – pLumo Jun 14 '18 at 8:24

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