Reputation: 430
I have a script which takes in a set of data, and command line options for several different outputs depending on what is desired at the time. Currently, even if nothing gets written to a file, the file is being created assumably because of the use of "with". Simplified code below illustrates my point. If the program is called with -a and -b options, 3 files with correct output are generated exactly as I want, but if either a or b is not wanted, "a.output" and "b.output" files are created with nothing in them.
import argparse
parser = argparse.ArgumentParser(description="description")
parser.add_argument("-a", "--a", action='store_true', default = False, help = "A type analysis")
parser.add_argument("-b", "--b", action='store_true', default = False, help = "b type analysis")
args = parser.parse_args()
master_dictionary = {}
if args.a:
master_dictionary["A"] = A_Function()
if args.b:
master_dictionary["B"] = B_Function()
master_dictionary["default"] = default_Function()
with open("a.output", "w") as A, open("b.output", "w") as B, open("default.output", "w") as default:
for entry in master_dictionary:
print>>entry, printing_format_function(master_dictionary[entry])
I am aware that i could collapse the printing options to go after the function call within the conditional, but in the actual script things are more complex and it is less ideal to put the print within the analysis blocks. I would like an answer that specifically modifies the with command. The goal is that "a.output" and "b.output" files only be created if they are going to contain text.
Upvotes: 1
Views: 110
Reputation: 251478
You can't stop the creation as part of the with
block. When you do with obj as A
, obj
has to exist before the with
block can do anything with it. The call open('a.output', 'w')
creates the file before the with
can have any say in the matter.
You could write your own contextmanager that would auto-delete the file at the end of the with
block, but that won't stop it from being created in the first place, and the code inside the block would have to somehow manually "signal" to the context manager to do the deletion (e.g., by setting some attribute on it).
It would probably be simpler to have a single-file with
block inside the loop. Something like this:
for output_file in files_to_create:
with open(output_file, 'w') as f:
# write to the file
Where files_to_create
is a list you populate before entering the loop, by looking at your options and adding files to the list only if the appropriate option was given. However, as I indicated in my comment, I think there are other problems with the way you're trying to handle this loop, so it's hard to know exactly what the code should look like.
Upvotes: 2