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>When to close a file? always - once you are finished working on it. Otherwise it will just hog memory.</p>

python