問(wèn)題描述
執(zhí)行以下操作并且不顯式處理文件對(duì)象并調(diào)用其 close()
方法是不好的做法嗎?
Is it bad practice to do the following and not explicitly handle a file object and call its close()
method?
for line in open('hello.txt'):
print line
注意 - 這適用于還沒(méi)有 with
語(yǔ)句的 Python 版本.
NB - this is for versions of Python that do not yet have the with
statement.
我問(wèn),因?yàn)?Python 文檔似乎建議這樣做:-
I ask as the Python documentation seems to recommend this :-
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
這似乎比必要的更冗長(zhǎng).
Which seems more verbose than necessary.
推薦答案
在處理文件時(shí),總是必須關(guān)閉,不要讓打開(kāi)的文件句柄到處都是.當(dāng)文件對(duì)象被垃圾回收時(shí),它們最終將被關(guān)閉,但您不知道何時(shí)會(huì)關(guān)閉,同時(shí)您將通過(guò)持有不再需要的文件句柄來(lái)浪費(fèi)系統(tǒng)資源.
Close is always necessary when dealing with files, it is not a good idea to leave open file handles all over the place. They will eventually be closed when the file object is garbage collected but you do not know when that will be and in the mean time you will be wasting system resources by holding to file handles you no longer need.
如果您使用的是 Python 2.5 及更高版本,則可以使用 with
語(yǔ)句自動(dòng)為您調(diào)用 close()
:
If you are using Python 2.5 and higher the close()
can be called for you automatically using the with
statement:
from __future__ import with_statement # Only needed in Python 2.5
with open("hello.txt") as f:
for line in f:
print line
這與您的代碼具有相同的效果:
This is has the same effect as the code you have:
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
with
語(yǔ)句是對(duì) Resource Acquisition Is Initialization的直接語(yǔ)言支持a> C++中常用的成語(yǔ).它允許安全使用和清理各種資源,例如它可以用于始終確保關(guān)閉數(shù)據(jù)庫(kù)連接或始終釋放鎖,如下所示.
The with
statement is direct language support for the Resource Acquisition Is Initialization idiom commonly used in C++. It allows the safe use and clean up of all sorts of resources, for example it can be used to always ensure that database connections are closed or locks are always released like below.
mylock = threading.Lock()
with mylock:
pass # do some thread safe stuff
這篇關(guān)于在 Python 文件對(duì)象上使用迭代器時(shí)是否需要 close()的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!