python script - generating a GeoJSON file for each shp file

1040
1
06-11-2020 05:58 AM
RafaelMichael
Occasional Contributor

I would like to write a python script in which the user enters the name of the directory with shapefile files. For each .shp file from a given directory (without checking subdirectories), the script generates a GeoJSON file in the current directory.

On the GitHub website I found a topic (https://gist.github.com/benbalter/5858851) in which someone may have written what I need:

But I need a script that first runs it, then in the console, the program asks the user for the path to the folder with the .shp files. In addition, if the GeoJSON file with the given name already exists, then before running the ogr2ogr command the program asks the user whether to overwrite it. Can you help me write such a program?

0 Kudos
1 Reply
RandyBurton
MVP Alum

As an alternative to ogr2ogr, you might consider Features to JSON.  If you are using Pro or Desktop 10.5+, there is an option to

Create output as GeoJSON, conforming to the GeoJSON specification.

I tested the following, to which you can add a walk through your shape file directory:

import arcpy
shp = r'C:\Path\To\file.shp'
out = r'C:\Path\To\file.json' # cannot use '.geojson' as extension

arcpy.FeaturesToJSON_conversion(shp, out, format_json="FORMATTED", geoJSON='GEOJSON')
# format_json is optional, makes file a bit more human readable

print('Done')