2

I'm trying to convert a large shapefile (more than 20,000 polygons) to a text file to use in a modelling software. It needs to be in a specific format which is number of nodes, followed by all x coordinates followed by all y coordinates with each polygon on a new line (Pictured below) (first line is total number of polygons).

screenshot of correct text file

Currently I am using QGIS 3.6.3 and saving the shapefile as a CSV using WKT geometry. This however does not include the number of nodes and coordinates are formatted as xy xy. Please note that I am not constrained to QGIS.

1

you can try this script:

open your python console in qgis and copy/paste the following code:

def extract_polygons(shapefile,lyrname,textfile):
    lyr = QgsVectorLayer(shapefile,lyrname, 'ogr')
    ft = lyr.getFeatures()
    with open(textfile, 'w') as o:
        for feature in ft:
            geom = feature.geometry()
            polygon = geom.asPolygon()
            xs = []
            ys = []
            for point in polygon[0]:
                xs.append(str(point[0]))
                ys.append(str(point[1]))

            number_of_nodes = str(len(polygon[0]))
            x_coords = ' '.join(xs)
            y_coords = ' '.join(ys)
            o.write('{} {} {} \n'.format(number_of_nodes, x_coords, y_coords))
#example
extract_polygons('path/to/your/shapefile/test.shp','test','path/to/output/file.txt')

Keep in mind that due to the fact that the first and the last node of a polygon are the same there may be some sanity issues (ie. square buildings with 5 points)

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.