Write GeoJson into a .geojson file with Python

Dumping a list of features directly does not create a valid GeoJSON file.

To create valid GeoJSON:

  1. Create a list of features (where each feature has geometry and optional properties)
  2. Create a collection (e.g. FeatureCollection) with those features
  3. Dump the collection to a file.

e.g.

from geojson import Point, Feature, FeatureCollection, dump

point = Point((-115.81, 37.24))

features = []
features.append(Feature(geometry=point, properties={"country": "Spain"}))

# add more features...
# features.append(...)

feature_collection = FeatureCollection(features)

with open('myfile.geojson', 'w') as f:
   dump(feature_collection, f)

Output:

{
    "type": "FeatureCollection",
    "features": [{
        "geometry": {
            "type": "Point",
            "coordinates": [-115.81, 37.24]
        },
        "type": "Feature",
        "properties": {
            "country": "Spain"
        }
    }]
}

To write a geojson object to a temporary file this function can be used:

import geojson
import tempfile

def write_json(self, features):
   # feature is a shapely geometry type
   geom_in_geojson = geojson.Feature(geometry=features, properties={})
   tmp_file = tempfile.mkstemp(suffix='.geojson')
   with open(tmp_file[1], 'w') as outfile:
      geojson.dump(geom_in_geojson, outfile)
   return tmp_file[1]