How to overwrite file completely using st_write?

When i run the code several times, i realized the size of the file is getting bigger, although i set append = FALSE

library(sf)

nc <- sf::st_read( system.file("./shape/nc.shp", package = "sf"))

sf::st_write(nc, dsn = "nc.geojson", append = FALSE)

You have likely seen the relevant warning message:

Warning message:
In CPL_write_ogr(obj, dsn, layer, driver, as.character(dataset_options),  :
  GDAL Error 6: DeleteLayer() not supported by this dataset.

The issue was raised by GeoJSON writer from GDAL; a GeoJSON file does not - unlike e.g. the OGC Geopackage, which is my favorite data format - support multiple layers.

It is therefore not practical to delete a layer before it gets written (which is what append = FALSE does).

You will have to force delete of the entire GeoJSON file before writing by setting delete_dsn = TRUE.

To double check: this piece of code

library(sf)

nc <- sf::st_read( system.file("./shape/nc.shp", package = "sf"))

sf::st_write(nc, dsn = "nc.geojson", append = FALSE, delete_dsn = TRUE)

will result in a file of a stable size, regardless of how many times the code is ran.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.