4

I have classes that can take a file as an argument, for example:

ParserClass(file('/some/file', 'rb'))

If I understand Python correctly, the file will be closed automatically once the object is garbage collected. What I don't understand is exactly when that happens. In a function like:

def parse_stuff(filename):
    parser = ParserClasss(file(filename, 'rb'))

    return list(parser.info())

Shouldn't that parser object be GC'd immediately after the function exits, causing the file to be closed? Yet, for some reason, Python appears to have the file open long after the function exits. Or at least it looks that way because Windows won't let me modify the file, claiming Python has it open and forcing me to to close IDLE.

Is there a way to ensure files are closed, short of explicitly asking for it for every file I create? I also want to add that these classes are external, I don't want to dig through them to find out exactly what they with the file.

2
  • 6
    It's worth noting that file() is not designed for opening files, use open() instead! Commented Oct 22, 2012 at 16:04
  • Change ParserClass to accept the path to the file and have ParserClass handle the openning and closing of the file, using the with statement to ensure the file is closed properly. Commented Oct 22, 2012 at 16:14

2 Answers 2

12

You can use the with statement to open the file, which will ensure that the file is closed.

with open('/some/file', 'rb') as f:
    parser = ParserClasss(f)
    return list(parser.info())

See http://www.python.org/dev/peps/pep-0343/ for more details.

2
  • I know I can do this. I was wondering if there was a shortcut or some way to close all open files.
    – Confluence
    Commented Oct 22, 2012 at 17:26
  • 2
    @Confluence No, you cannot. The only thing Python (or any other GC'd language for that matter) can figure out automatically is when an object cannot possibly be in use anymore, and even then it may only notice that long after it becomes unreachable. Even if it could always detect unreachability immediately, that's still not (consider f = open(...); read_but_dont_close(f); do_a_lot_of_work()). Just get used to with. Even ignoring the technical benefits, it makes the period of use explicit, and explicit is better than implicit.
    – user395760
    Commented Oct 22, 2012 at 19:20
6

You can use with to open files. When you use with, the file will be implicitly closed when the with block is exited, and it will handle exception states as well.

1
  • 2
    +1 for mentioning the fact that with also handles exceptions well - it's a really important point. Commented Oct 22, 2012 at 16:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.