Sometimes when using ipython you might hit an exception in a function which has opened a file in write mode. This means that the next time you run the function you get a value error,
ValueError: The file 'filename' is already opened. Please close it before reopening in write mode.
However since the function bugged out, the file handle (which was created inside the function) is lost, so it can't be closed. The only way round it seems to be to close the ipython session, at which point you get the message:
Closing remaining open files: filename... done
Is there a way to instruct ipython to close the files without quitting the session?
You should try to always use the
with
statement when working with files. For example, use something likeThis 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 exampleThe finally block contains code which should be run after any
try
,except
orelse
block, even if an exception occured. From the documentation: