0

When working with files in Python2.7 (using the iPython console of the Spyder IDE, I'm not sure if this behavior is general to all IDE's) I've noticed that even if you use a with block, the active python shell retains the file in an open state until the shell is closed. This behavior is extremely annoying as I cant simply delete a file without first closing the current Python session. Is there a way to bypass this behavior?

Here's the code that I'm running to observe this behavior:

if __name__=='__main__':
    logger=logging.getLogger('CopasiTools')
    logger.setLevel(logging.DEBUG)
    log_filename=os.path.join(os.getcwd(),'fileQuestionExample.log')

    handler=logging.FileHandler(log_filename,mode='w')
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.debug('example debug')
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • Can you build an [MVCE](https://stackoverflow.com/help/mcve)? Because this simply doesn't reproduce in the general case. Which file are you referring to? Is it possible that your IDE tries to scan the file and thus the IDE holds the open file handle? – dhke Jul 16 '16 at 09:37
  • Sure, please see the question above. And I don't know - but it would make sense if it does. – CiaranWelsh Jul 16 '16 at 09:41
  • And you are referring to the file in the logger FileHandler? In this case, you have a much more specific problem: The logger keeps the file open because you still have a logger. See [python does not release filehandles to logfile](https://stackoverflow.com/questions/15435652/python-does-not-release-filehandles-to-logfile) – dhke Jul 16 '16 at 09:47
  • Yes this is the answer! Thanks very much. Just to note though, the reason I posed the question in a general way is because I've noticed the behavior before in other contexts. I guess I've been relying too much on `with` statements. If you want to write an answer, I'll accept. – CiaranWelsh Jul 16 '16 at 09:56

0 Answers0