Thursday, June 17, 2021

PyQGIS - Convert from one vector format to another

 If you got a valid QgsVectorLayer, then the following class "QgsVectorFileWriter.writeAsVectorFormat(...)" is used to convert any gdal/ogr supported vector driver format to another.

There are many vector drivers supported by GDAL/OGR as listed on this page.

For example, to convert GeoJSON to Shapefile, we will read the GeoJSON file using QgsVectorLayer and convert it to ESRI Shapefile driver using QgsVectorFileWriter.writeAsVectorFormat(...) as demonstrated below.



# Convert GeoJSON to SHP
input_shp = QgsVectorLayer(r"C:\Users\Yusuf_08039508010\Desktop\US Zip Codes\ak_alaska_zip_codes_geo.min.json","polygon","ogr")
input_shp.isValid() 

QgsVectorFileWriter.writeAsVectorFormat(input_shp, r"C:\Users\Yusuf_08039508010\Desktop\US ZipCode\poly.shp" , "UTF-8", input_shp.crs(), "ESRI Shapefile")

# ----------------------------------------- for Bulk Conversion
import glob

input_files = glob.glob(r'C:\Users\Yusuf_08039508010\Desktop\Working_Files\GIS Data\US Zip Codes\*.json')
for f in input_files:
    out_filename = f.split('\\')[-1].split('.')[0]
    input_file = QgsVectorLayer(f, "polygon", "ogr")
    
    if input_file.isValid() == True:
        QgsVectorFileWriter.writeAsVectorFormat(input_file, rf"C:\Users\Yusuf_08039508010\Desktop\Working_Files\SHP\US ZipCode\{out_filename}.shp", "UTF-8", input_file.crs(), "ESRI Shapefile")
    else:
        print(f, 'is not a valid input file')
        
print('Done Processing..., ', f)


Note that "QgsVectorFileWriter.writeAsVectorFormat(...)" takes in the following; the input file, the output file, the encoding, the coordinate system, the output file driver.

That is it!

No comments:

Post a Comment