From ef6bd32d68815d25fe05eae11b16ea786e36ff28 Mon Sep 17 00:00:00 2001 From: Markus Rosenstihl Date: Sun, 12 Jul 2026 10:45:37 +0200 Subject: [PATCH] cleanup of write_to_csv in MeasurementResult (fixes #30) Leaking file handle when exception occurs during write --- src/damaris/data/MeasurementResult.py | 42 +++++++++++++-------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/src/damaris/data/MeasurementResult.py b/src/damaris/data/MeasurementResult.py index c96c731..d81c1c9 100644 --- a/src/damaris/data/MeasurementResult.py +++ b/src/damaris/data/MeasurementResult.py @@ -1,6 +1,5 @@ import threading import math -import types import sys import tables import numpy @@ -45,7 +44,7 @@ class AccumulatedValue: def __add__(self,y): new_one=AccumulatedValue() - if (type(y) is types.InstanceType and isinstance(y, AccumulatedValue)): + if isinstance(y, AccumulatedValue): new_one.y=self.y+y.y new_one.y2=self.y2+y.y2 new_one.n=self.n+y.n @@ -56,7 +55,7 @@ class AccumulatedValue: return new_one def __iadd__(self,y): - if (type(y) is types.InstanceType and isinstance(y, AccumulatedValue)): + if isinstance(y, AccumulatedValue): self.y+=y.y self.y2+=y.y2 self.n+=y.n @@ -203,28 +202,27 @@ class MeasurementResult(Drawable.Drawable, collections.UserDict): destination can be a file or a filename suitable for further processing """ - the_destination=destination - file_opened = False - if type(destination) in (str,): - the_destination=open(destination, "w") - file_opened = True + if isinstance(destination, str): + with open(destination, "w") as f: + self._write_to_csv_dest(f, delimiter) + else: + self._write_to_csv_dest(destination, delimiter) - the_destination.write("# quantity:"+str(self.quantity_name)+"\n") - the_destination.write("# x y ysigma n\n") + def _write_to_csv_dest(self, dest, delimiter): + dest.write("# quantity:"+str(self.quantity_name)+"\n") + dest.write("# x y ysigma n\n") for x in self.get_xdata(): - y=self.data[x] - if type(y) in [float, int, int]: - the_destination.write("%e%s%e%s0%s1\n"%(x, delimiter, y, delimiter, delimiter)) + y = self.data[x] + if isinstance(y, (float, int)): + dest.write("%e%s%e%s0%s1\n" % (x, delimiter, y, delimiter, delimiter)) else: - the_destination.write("%e%s%e%s%e%s%d\n"%(x, - delimiter, - y.mean(), - delimiter, - y.mean_error(), - delimiter, - y.n)) - if file_opened: - the_destination.close() + dest.write("%e%s%e%s%e%s%d\n" % (x, + delimiter, + y.mean(), + delimiter, + y.mean_error(), + delimiter, + y.n)) def write_to_hdf(self, hdffile, where, name, title, complib=None, complevel=None):