How to convert a shapefile data into another format like KML, dxf, Geopackage, etc using PyQGIS? In this PyQGIS tutorial series we'll see how to do it.
To convert a shapefile into another format, simply we are using QgsVectorFileWriter class with writeAsVectorFormat method. This writeAsVectorFormat method supports GDAL/OGR vector driver. It means we can convert a shapefile into numerous vector format which is supported by GDAL/OGR. Check out GDAL/OGR vector drivers to see a list of supported data format.
The following expression shows general format to convert a shapefile into another vector format in PyQGIS.
output file:string,encode:string,coordinate system:QgsCoordinateReferenceSystem,
The expression above just using some basic parameters for a shapefile conversion. The first parameter is input shapefile which is in QGSVectorLayer class. The next one, output file specifies the output file of converted shapefile. Encoding defines the the encoding type. Coordinate system is used to determine the coordinate system of output file, it has to be in QgsCoordinateReferenceSystem class.The last one is OGR driver which must be defined depends on the format of output file. For a complete parameter please refer to PyQGIS documentation.
Now let's use it in a real example.
As mentioned above, the first parameter is input shapefile which has to be a QGS vector layer. Therefore we have to open an input shapefile with QGSVectorLayer class. Furthermore to check if a shapefile is valid or not can be used isValid method.
Firstly let's convert the input shapefile into Geopackage format. To convert a shapefile into Geopackage format GPKG ogr vector driver is used.
Next, the following code convert a shape file into geojoson and KML using OGR driver GeoJSON and KML.
#SHP TO GeoJSON QgsVectorFileWriter.writeAsVectorFormat(input_shp,"F:\polygon.gpkg","UTF-8",input_shp.crs(),"GeoJSON") #SHP TO KML QgsVectorFileWriter.writeAsVectorFormat(input_shp,"F:\polygon.kml","UTF-8",input_shp.crs(),"KML")
To convert a shapefile into another format, we just change the output file name extension and OGR driver as can be found in OGR vector drivers.
Lastly to verify the output of converted shapefile, open the output file in QGIS or another specified software. If the output file can be seen, then the conversion is working fine. The image below is an example of shapefile conversion into KML format which is viewed in Google Earth.
Figure. Shapefile to KML conversion output
That's all the tutorial how to convert a shapefile into another vector format like Geopackage, GeoJSON, KML and many more using PyQGIS. If you are interested to learn more about PyQGIS, please see other tutorials which discuss other topics in this QGIS python programming tutorial series.