Skip to content

Commit 762e504

Browse files
committed
close netcdf file if exception occurrs during writing
1 parent 7863ea5 commit 762e504

2 files changed

Lines changed: 18 additions & 6 deletions

File tree

ncwriter/template.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -351,10 +351,15 @@ def to_netcdf(self, outfile, var_args={}, **kwargs):
351351
if not self.is_dim_consistent():
352352
raise ValueError("Dimensions.")
353353

354-
self.ncobj = netCDF4.Dataset(self.outfile, mode='w', **kwargs)
355-
self.create_dimensions()
356-
self.create_variables(**var_args)
357-
self.create_global_attributes()
358-
self.ncobj.sync()
359-
self.ncobj.close()
354+
try:
355+
self.ncobj = netCDF4.Dataset(self.outfile, mode='w', **kwargs)
356+
self.create_dimensions()
357+
self.create_variables(**var_args)
358+
self.create_global_attributes()
359+
self.ncobj.sync()
360+
except Exception:
361+
raise
362+
finally:
363+
self.ncobj.close()
364+
360365
self.ncobj = netCDF4.Dataset(self.outfile, 'a')

test_ncwriter/test_template.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,13 @@ def test_fill_values_from_masked_array(self):
225225
self.assertTrue(dsx[:5].mask.all())
226226
self.assertTrue((dsx[5:] == x[5:]).all())
227227

228+
def test_close_file_on_exception(self):
229+
template = DatasetTemplate.from_json(TEMPLATE_JSON)
230+
self.assertIsNone(template.ncobj)
231+
self.assertRaises(ValueError, template.to_netcdf, self.temp_nc_file)
232+
self.assertFalse(template.ncobj.isopen())
233+
234+
228235
# TODO: add data from multiple numpy arrays
229236
# e.g. template.add_data(TIME=time_values, TEMP=temp_values, PRES=pres_values)
230237
# TODO: add data from Pandas dataframe (later...)

0 commit comments

Comments
 (0)