2

If I wanted to close a file in a program with an infinite loop, I could do the following:

file = open('abc', 'w')

while True:
    try:
        file.write('a\n')
    except KeyboardInterrupt:
        break

file.close()

But if I just left it like this:

file = open('abc', 'w')

while True:
    file.write('a\n')

Would the file not get closed on exit?

Novice
  • 575
  • 2
  • 7
  • 16
  • Possible duplicate of [Do files get closed during an exception exit?](http://stackoverflow.com/questions/17577137/do-files-get-closed-during-an-exception-exit) – Lex Scarisbrick Jul 20 '16 at 03:09

2 Answers2

-1

Python has automatic garbage collection. Garbage collection is the automatic clearing away of unused file handles or data in memory. As a python program halts, if it has halted cleanly, it will free up the memory and file handles it has used as it closes. It's prudent to have a familiarity with how garbage collection works when writing programs that run for extended periods of time, or that access a lot of information or files.

mjac
  • 264
  • 2
  • 9
  • 4
    Files being closed when a program exits has nothing to do with garbage collection. – chepner Jul 20 '16 at 03:24
  • I guess that depends on what you mean by "closed." If a python program has exited, either from an interrupt, or from ending normally, it is going to release all file handles it has open. In perl, which I'm much more familiar with, if a function that has opened a file is exited, and the garbage collector determines the file handle has no more references, the file handle will be released and the file will be 'closed.' If you're worried about file locks, that's pretty conditional. And not relevant to the program example. – mjac Jul 20 '16 at 05:06
  • Also other [great answers](http://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important) to the same question – mjac Jul 20 '16 at 05:14
-1

As mentioned above by @Mitch Jackson, if a python program halts cleanly, it will free up the memory. In your case, since you are just opening a file in a while loop. The program won't be able to close already opened file when it halts unless you explicitly include exception handling like a try-catch block or a with statement which wraps it up.

Here are the documentation on with statement: docs

Rajat Vij
  • 689
  • 1
  • 6
  • 12