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
Answer
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.
No comments:
Post a Comment