Python >> Tutoriel Python >  >> Python Tag >> JSON

Écrire GeoJson dans un fichier .geojson avec Python

Le vidage direct d'une liste d'entités ne crée pas de fichier GeoJSON valide.

Pour créer un GeoJSON valide :

  1. Créer une liste d'entités (où chaque entité a une géométrie et des propriétés facultatives)
  2. Créer une collection (par exemple FeatureCollection) avec ces fonctionnalités
  3. Vider la collection dans un fichier.

par exemple.

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)

Sortie :

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

Pour écrire un objet geojson dans un fichier temporaire, cette fonction peut être utilisée :

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]