How do you know when to close a file in python?
<pre><code>from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)


in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
#above is the original code. 
</code></pre>

<p>He closes the files above. But then in the- common student questions- there is this. </p>

<p>Q. When I try to make this script shorter I get an error when I close the     files at the end.</p>

<p>A.    You probably did something like this, indata = open(from_file).read(), which means you don't need to then do in_file.close() when you reach the end of the script. It should already be closed by Python once that one line runs.</p>

<p>so,how do you know when to close the file and when not to?</p>

<p>Thank you everyone,i got it! :)</p>

<p>From <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">methods-of-file-objects</a>.  </p>

<blockquote>
  <blockquote>
    <blockquote>
      <p>It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite 
      finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:</p>
    </blockquote>
  </blockquote>
</blockquote>

<pre><code>&gt;&gt;&gt; with open('workfile', 'r') as f:
...     read_data = f.read()
&gt;&gt;&gt; f.closed
True
</code></pre>

python