1

Possible Duplicate:
Does filehandle get closed automatically in Python after it goes out of scope?

I am new to python. i know if you open a file and write it, you need to close it at the end.

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

out_file = open(to_file, 'w')
out_file.write(indata)

out_file.close()
in_file.close()

if I write my code this way.

open(to_file, 'w').write(open(from_file).read())

I cannot really close it, will it be automatically closed?

Community
  • 1
  • 1
qinking126
  • 11,385
  • 25
  • 74
  • 124

3 Answers3

8

It will eventually be closed, but there is no guarantee as to when. The best way to do this when you need to handle such things is a with statement:

with open(from_file) as in_file, open(to_file, "w") as out_file:
    out_file.write(in_file.read())

# Both files are guaranteed to be closed here.

See also: http://preshing.com/20110920/the-python-with-statement-by-example

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
6

The Python garbage collector will close the file automatically for you when it destroys the file object, but you don't have a lot of control over when that actually happens (thus, the bigger problem is that you won't know if an error / exception happens during the file close)

The preferred way to do this after Python 2.5 is with the with structure:

with open("example.txt", 'r') as f:
    data = f.read()

And the file is guaranteed to be closed for you after you are done with it, regardless of what happens.

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
1

According to http://pypy.org/compat.html, CPython will close the file; however PyPy will close the file only when garbage collector runs. So for compatibility and style reasons it is better to close the file explicitly (or using with construct)

Yevgen Yampolskiy
  • 7,022
  • 3
  • 26
  • 23
  • to be precise, when GC runs or interpreter exits. CPython will never close the file that's in a GC cycles. – fijal Jan 02 '13 at 22:54