Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Don't worry about it. Python's garbage collector is good, and I've never had a problem with not closing file-pointers (for read operations at least)</p> <p>If you did want to explicitly close the file, just store the <code>open()</code> in one variable, then call <code>readlines()</code> on that, for example..</p> <pre><code>f = open("thefile.txt") all_lines = f.readlines() f.close() </code></pre> <p>Or, you can use the <code>with</code> statement, which was added in Python 2.5 as a <code>from __future__</code> import, and "properly" added in Python 2.6:</p> <pre><code>from __future__ import with_statement # for python 2.5, not required for &gt;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() </code></pre> <p>The file will automatically be closed at the end of the block.</p> <p>..but, there are other more important things to worry about in the snippets you posted, mostly stylistic things.</p> <p>Firstly, try to avoid manually constructing paths using string-concatenation. The <a href="http://docs.python.org/library/os.path.html" rel="nofollow noreferrer"><code>os.path</code></a> module contains lots of methods to do this, in a more reliable, cross-platform manner.</p> <pre><code>import os y = open(os.path.join(dir, file), 'r') </code></pre> <p>Also, you are using two variable names, <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow noreferrer"><code>dir</code></a> and <a href="http://docs.python.org/library/functions.html#file" rel="nofollow noreferrer"><code>file</code></a> - both of which are built-in functions. <a href="http://www.logilab.org/857" rel="nofollow noreferrer">Pylint</a> is a good tool to spot things like this, in this case it would give the warning:</p> <pre><code>[W0622] Redefining built-in 'file' </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload