Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring files are closed in Python

Tags:

python

file-io

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.

like image 489
Confluence Avatar asked Dec 02 '22 21:12

Confluence


2 Answers

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.

like image 95
Nathan Villaescusa Avatar answered Dec 15 '22 10:12

Nathan Villaescusa


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.

like image 36
Silas Ray Avatar answered Dec 15 '22 09:12

Silas Ray