xralf xralf - 1 month ago 5
Python Question

Closing and opening files between conditions

I have a for cycle and inside of it a condition.
If the condition holds I'd like to create a file with certain name and write to it. If the condition does not hold I'd like to only write to file created in previous iterations.

The file name depends on x[0].

I haven't run it because it's clear that it won't run. How would you deal with the conditional closing and opening of files (always with new name)?

for x in dd:
if x[1]: # close old file and start to write to new file
...
f.close() # close the file (will not work in first iteration)
fileName = "_".join(matchList) # create sensible file name
f = open(fileName, "w")
f.write(x[0])
else:
f.write(x[0])

Answer
my_file = something_that_creates_the_first_file()

for x in dd:
    if x[1]:  # Close old file and start to write to new file
        my_file.close()
        fileName = "_".join(matchList) # create sensible file name
        my_file = open(fileName, "w")

    my_file.write(x[0])

my_file.close()

Alternatively, you might be able to open and close the file every loop iteration, in which case you can do:

fileName = something_that_creates_the_first_file_name()

for x in dd:
    if x[1]:  # Close old file and start to write to new file
        fileName = "_".join(matchList) # create sensible file name

    with open(fileName, "a") as my_file:
        my_file.write(x[0])

This latter approach uses the built-in context management handlers for files to ensure if there are any errors, there is never a file left open.