Monday 4 June 2018

Why close a dataset in GDAL Python?


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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...