scarecrow scarecrow - 1 month ago 16
Python Question

How do you know when to close a file in python?

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! :)

Answer

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
Comments