You should try to always use the with
statement when working with files. For example, use something like
with open("x.txt") as fh:
...do something with the file handle fh
This ensures that if something goes wrong during the execution of the with
block, and an exception is raised, the file is guaranteed to be closed. See the with documentation for more information on this.
Edit: Following a discussion in the comments, it seems that the OP needs to have a number of files open at the same time and needs to use data from multiple files at once. Clearly having lots of nested with
statements, one for each file opened, is not an option and goes against the ideal that "flat is better than nested".
One option would be to wrap the calculation in a try
/finally
block. For example
file_handles = []
try:
for file in file_list:
file_handles.append(open(file))
# Do some calculations with open files
finally:
for fh in file_handles:
fh.close()
The finally block contains code which should be run after any try
, except
or else
block, even if an exception occured. From the documentation:
If finally
is present, it specifies a "cleanup" handler. The try
clause is executed, including any except
and else
clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally
clause is executed. If there is a saved exception, it is re-raised at the end of the finally
clause. If the finally
clause raises another exception or executes a return or break statement, the saved exception is lost. The exception information is not available to the program during execution of the finally
clause.