使用时open
,请尝试将其用作上下文管理器。这样,无论发生什么,当你完成它时它都会关闭:
with open('file.txt', 'r') as fin:
# Access fin like normal
# No matter what happens, after the block, it's closed!
或者,您可以用您自己的函数替换实例open
并为您执行一些额外的日志记录:close
def my_open(filename, *args):
logger.debug('Opening %s' % filename)
return open(filename, *args)
def my_close(file_obj):
logger.debug('Closing %s' % file_obj.name)
return file_obj.close()
作为最后的手段,如果您无法访问有问题的代码,或者更改它会很麻烦,您可以尝试猴子修补功能。
import traceback
class MyFile(file):
@staticmethod
def open(*args, **kwargs):
return MyFile(*args, **kwargs)
def __init__(self, *args, **kwargs):
self._file = self._open(*args, **kwargs)
print('Opening %s from %s' % (
self._file.name, ''.join(traceback.format_stack())))
def close(self):
print('Closing file %s from %s' % (
self._file.name, ''.join(traceback.format_stack())))
self._file.close()
# Now the monkey-patching
file = MyFile
MyFile._open = open
open = MyFile.open
o = open('hello', 'w+')
它当然不是世界上最漂亮的东西,但如果你能够对其进行猴子补丁,那么你至少能够处理遗留代码。