python – How to Convert GeoJSON to OSM XML Using Python

geojsonopenstreetmappython

I know about using ogr2ogr, and also about the nodejs module osm_geojson. However, I would like to convert GeoJSON to OSM XML from Python. Is there a library which has this capability built in? Or would I have to write custom code based on the OSM XML specification?
I am processing the GeoJSON using geopandas, so exporting directly from geopandas to OSM would also work.

I have looked at the GDAL/OGR Python library.
It may be able to do what I want, but the documentation is impenetrable. The Cookbook has something similar to what I am looking for, but I can't quite seem to piece it together.

My code currently looks like this:

from osgeo import ogr
import os

# Read GeoJSON file
geojson_file = 'file.geojson'
GeoJSON_driver = ogr.GetDriverByName('GeoJSON')
data = GeoJSON_driver.Open(geojson_file, 0)
layer = data.GetLayer()

# OSM file to write
osm_file = 'file.osm'
OSM_driver = ogr.GetDriverByName('OSM')

# Remove output file if it already exists
if os.path.exists(osm_file):
    OSM_driver.DeleteDataSource(osm_file)

# Export data to OSM file
# This is where I'm stuck

Best Answer

There is a Python tool ogr2osm.py available here https://github.com/pnorman/ogr2osm.