Use contextlib.closing for correct resource management