次のコードを使用してcsvファイルを読み取ります
f = csv.reader(open(filename, 'rb'))
だったら閉めるわけないじゃないfilename
ですか。そうすることの害はありますか、それともそれを読むためのより良い方法はありますか?
コンテキストマネージャーを使用します:
with open(filename, 'rb') as handle:
f = csv.reader(handle)
一般に、開いている未使用のファイル記述子はリソース リークであり、回避する必要があります。
興味深いことに、ファイルの場合、ファイルへの参照がなくなるとすぐに、少なくともファイル記述子が解放されます (この回答も参照してください)。
#!/usr/bin/env python
import gc
import os
import subprocess
# GC thresholds (http://docs.python.org/3/library/gc.html#gc.set_threshold)
print "Garbage collection thresholds: {}".format(gc.get_threshold())
if __name__ == '__main__':
pid = os.getpid()
print('------- No file descriptor ...')
subprocess.call(['lsof -p %s' % pid], shell=True)
x = open('/tmp/test', 'w')
print('------- Reference to a file ...')
subprocess.call(['lsof -p %s' % pid], shell=True)
x = 2
print('------- FD is freed automatically w/o GC')
subprocess.call(['lsof -p %s' % pid], shell=True)