-1
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. 

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

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

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.

so,how do you know when to close the file and when not to?

Thank you everyone,i got it! :)

2 Answers2

3

From methods-of-file-objects.

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:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True
0

When to close a file? always - once you are finished working on it. Otherwise it will just hog memory.

maze88
  • 850
  • 2
  • 9
  • 15
  • True, but the safest and cleanest way to do that is to use `with`, rather than explicitly calling the file's `.close` method yourself. – PM 2Ring Oct 02 '16 at 07:44