What you are trying to do is cause late creation of the file. What you want is something that looks like a context manager, but doesn't actually create the file until you need it. You'll need to implement __enter__
and __exit__
yourself. This is a (very) abbreviated example, compare to a full one, just for your exact case:
class LateFile(object):
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.fp = None
def __enter__(self):
# Do nothing - we don't open the file yet
return(self)
def __exit__(self, exctype, value, traceback):
if self.fp != None:
fp.close()
def write(self, *args, **kwargs):
if self.fp == None:
self.fp = open(self.filename, self.mode)
self.fp.write(*args, **kwargs)
Something along those lines.
And then, to use it, do something like:
with LateFile(filename, "w") as output:
for item in items:
result = compute_stuff(item)
if should_write_result(item, result):
write_result(item, result, output)
results.append(result)
write_result
should see output
as a normal file object; you'll need to reflect or delegate the methods down to it. Doing this, if no results are written, the file will not be created, but if even one result is written, the file will be created & written to.