I see quite often in Python GDAL code that people close datasets at the end of their script. Why does it makes sense to close a dataset in Python GDAL? Are there any consequences if I don't do it?

import gdal

# open dataset
ds = gdal.Open('test.tif')

# close dataset
ds = None
  • Sometimes the C++ destructor does things other than clean up(for some drivers), such as recomputing statistics. It's good practice to set to None, everything blah238 says is correct as well AFAIK.
    – user10353
    Commented Dec 13, 2013 at 16:25

1 Answer 1


I do not think this has any purpose at the end of the script, as the Python garbage collector will do the same thing automatically when the script exits. The reason you might want to do it is in the middle of your script, to recover the resources held by accessing the dataset, remove file locks, etc. so that you can reuse them.

del ds should have the same effect but is more clear as to its intent.

The more Pythonic approach would be to use a with statement, but GDAL/OGR does not implement it. However, there are some GDAL/OGR wrappers like Rasterio and Fiona that do.

  • 3
    Consider Python file objects. You open one with f = open(filename) and you close one with f.close(). Not del f or f = None. Why? Because what happens to objects after they are no longer referenced is a detail of the interpreter's implementation and because explicit is better than implicit (python.org/dev/peps/pep-0020).
    – sgillies
    Commented Dec 17, 2013 at 3:34
  • 1
    Agreed, but the GDAL Python bindings aren't exactly Pythonic. There is a GDALClose() method that should be called if you want to be explicit (I see that Rasterio calls this internally).
    – blah238
    Commented Dec 17, 2013 at 3:50
  • 3
    In Python, GDALClose() has not been implemented but setting the dataset to None (i.e., ds = None) is equivalent.
    – Arthur
    Commented Jan 30, 2015 at 19:57
  • @Arthur It is not.
    – s-m-e
    Commented May 21, 2021 at 12:14
  • anyway gdal python wrapper has a design flaw, you can't rely on garbage collector to close a dataset, e.g. in pypy it would be garbaged later
    – sherpya
    Commented Sep 27, 2022 at 0:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.