是否真的有必要使用python语句来确保文件被关闭?

时间:2015-03-20 17:34:22

标签: python file with-statement

通常说在使用python中的文件时应该使用with语句,这样无论文件上的操作是否成功,文件都将被关闭。例如:

with open('somefile') as f:
    # do stuff to file

而不是像:

try:
    f = open('somefile')
    # do stuff to file
except Exception as e:
    print 'error: %s' % e
finally:
    f.close()

但是,我也听说过Python的GC无论如何都要照顾它,所以没有必要。

这是真的吗?如果是这样,为什么这是一种常见的模式呢?

0 个答案:

没有答案