title: Ensuring files are closed in Python
body: <p>I have classes that can take a file as an argument, for example:</p>
  
  <pre><code>ParserClass(file('/some/file', 'rb'))
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>def parse_stuff(filename):
      parser = ParserClasss(file(filename, 'rb'))
  
      return list(parser.info())
  </code></pre>
  
  <p>Shouldn't that <code>parser</code> 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.</p>
  
  <p>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.</p>