Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

file - Does filehandle get closed automatically in Python after it goes out of scope?

If I do the following, does filehandle get closed automatically as it goes out of scope in Python:

def read_contents(file_path):
  return file(file_path).read()

If it doesn't, how can I write this function to close the scope automatically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is thrown in the function and file is not explicitly closed using a with statement or a try:...finally: then a reference to the file will be kept as part of the stack trace in the traceback object and the file will not be closed, at least until the next exception is thrown.

Also IronPython and Jython use the garbage collection facilities of the .Net CLR and Java JVM respectively. These are not reference counted, so the file will remain open indefinitely until the garbage collector decides to reclaim the object's memory or the program terminates.

So in general it is important to explicitly close the file using either with: or try:...finally:.

Of course all this is holds true for any other type of object that requires explicit cleanup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...