關於你的代碼奇怪的是,如果它傳遞一個打開的文件,它會關閉它。這不好。無論打開哪個代碼,該文件都應負責關閉它。這使得功能稍微複雜一些,但:
def awesome_parse(path_or_file):
if isinstance(path_or_file, basestring):
f = file_to_close = open(path_or_file, 'rb')
else:
f = path_or_file
file_to_close = None
try:
return do_stuff(f)
finally:
if file_to_close:
file_to_close.close()
您可以抽象送人通過編寫自己的上下文管理器:
@contextlib.contextmanager
def awesome_open(path_or_file):
if isinstance(path_or_file, basestring):
f = file_to_close = open(path_or_file, 'rb')
else:
f = path_or_file
file_to_close = None
try:
yield f
finally:
if file_to_close:
file_to_close.close()
def awesome_parse(path_or_file):
with awesome_open(path_or_file) as f:
return do_stuff(f)
噢......當它不應該關閉文件時,它很好用!我絕對不希望這樣的事情發生。謝謝! – TorelTwiddler
不應該'產量'是'產量f'? –
「@ contextlib.contextmanager」到底做了什麼?爲什麼沒有它會得到'AttributeError:__exit__'?謝謝! –