I have this simple code which should write an empty GeoJSON.
import geopandas as gpd
gpd.GeoDataFrame(geometry=[]).to_file("test", driver="GeoJSON")
However, the library thinks it's smart and throws the following exception.
Traceback (most recent call last):
File "/tmp/ipykernel_2102262/1921918865.py", line 1, in <module>
gpd.GeoDataFrame(geometry=[]).to_file("test", driver="GeoJSON")
File "/home/lukas/anaconda3/envs/tf_gpu/lib/python3.9/site-packages/geopandas/geodataframe.py", line 1086, in to_file
_to_file(self, filename, driver, schema, index, **kwargs)
File "/home/lukas/anaconda3/envs/tf_gpu/lib/python3.9/site-packages/geopandas/io/file.py", line 304, in _to_file
schema = infer_schema(df)
File "/home/lukas/anaconda3/envs/tf_gpu/lib/python3.9/site-packages/geopandas/io/file.py", line 362, in infer_schema
raise ValueError("Cannot write empty DataFrame to file.")
ValueError: Cannot write empty DataFrame to file.
What's the best way to prevent this and have Geopandas write the file regardless?
One thing I can do is comment out the offending code in geopandas.io.file.py/infer_schema
:
# if df.empty:
# raise ValueError("Cannot write empty DataFrame to file.")
geom_types = _geometry_types(df)
schema = {"geometry": geom_types, "properties": properties}
return schema
That solves the problem but I'm not keen on forking Geopandas because of a tiny issue like this and then missing out on all new features.
My ideal solution would be to get this changed to a warning in Geopandas upstream but that requires consensus and time.
I'm aware of contextlib.suppress
but that only suppresses the error at the level outside the context manager, after all the calls to GeoPandas have exited, so the file is not written.
I'm not interested in any workarounds for writing the GeoJSON any other way as that would be more complicated than commenting out the two lines or monkey-patching the infer_schema
method. This question is just asking if it is at all possible to just tell Python to ignore the exception completely and continue execution at geom_types = _geometry_types(df)
.