4

Possible Duplicate:
Is close() necessary when using iterator on a Python file object

for line in open("processes.txt").readlines():
    doSomethingWith(line)

Take that code for example. There's nothing to call close() on. So does it close itself automatically?

Community
  • 1
  • 1
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • If you never close it, it remains open in memory. It will not auto close. – Matt Clark Dec 06 '12 at 05:49
  • So is this an inadvisable code snippet? I was under the impression that format was common. Unless I just follow it with close("processes.txt")...? Of course... – temporary_user_name Dec 06 '12 at 05:50
  • This would be okay if you closed the reader. I would recommend using as Snakes mentioned: with() -> this will guarantee that you will close the reader when you are done doing what you need with the file. – Matt Clark Dec 06 '12 at 05:55
  • I don't get it. If we don't have a reference to file object, and we finished to read lines from it - I mean, we're not in the `for`'s scope anymore, then python's garbage collector has to clean it, right? Or not? – aga Dec 06 '12 at 06:11

2 Answers2

7

Files will close when the corresponding object is deallocated. The sample you give depends on that; there is no reference to the object, so the object will be removed and the file will be closed.

Important to note is that there isn't a guarantee made as to when the object will be removed. With CPython, you have reference counting as the basis of memory management, so you would expect the file to close immediately. In, say, Jython, the garbage collector is not guaranteed to run at any particular time (or even at all), so you shouldn't count on the file being closed and should instead close the file manually or (better) use a with statement.

Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
5

AFAIK they don't. In order to have autoclosing, you need to use a context manager, such as with

Although the object itself may be reclaimed by garbage collection and closed, there is no definite time to when garbage collection occurs.

with open("processes.txt") as openfile:
    <do stuff>
Snakes and Coffee
  • 8,747
  • 4
  • 40
  • 60