Do not worry about it. The Python garbage collector is good, and I never had a problem closing file pointers (for read operations at least)
If you want to explicitly close the file, just save open() in one variable, and then call readlines() on this, for example ..
f = open("thefile.txt") all_lines = f.readlines() f.close()
Or you can use the with statement, which was added in Python 2.5 as an import from __future__ and "correctly" added in Python 2.6:
from __future__ import with_statement # for python 2.5, not required for >2.6 with open("thefile.txt") as f: print f.readlines() # or the_file = open("thefile.txt") with the_file as f: print f.readlines()
The file will be automatically closed at the end of the block.
.. but there are other more important things to worry about in the snippets you posted, mostly stylistic things.
First, try to avoid manually constructing paths by concatenating strings. The os.path module contains many ways to make this a more reliable cross-platform way.
import os y = open(os.path.join(dir, file), 'r')
In addition, you use two variable names, dir and file - both of which are built-in functions. Pylint is a good tool for detecting such things, in which case it will give a warning:
[W0622] Redefining built-in 'file'
source share