如何关闭我从未分配给变量的文件对象?

时间:2012-02-24 07:30:13

标签: python file resources

from sys import argv
script, origin, destination = argv

open(destination, 'w').write(open(origin).read())

如何关闭目标和源文件对象?或者这是我不需要担心的事情?

1 个答案:

答案 0 :(得分:6)

简而言之,您不应该担心这些问题,但在较大的程序中,您可能会用完文件描述符。

从版本2.5开始,Python有with语句,可以为你关闭文件:

from __future__ import with_statement # Only required for Python 2.5
with open(destination, 'w') as dest:
   with open(origin) as orig:
        dest.write(orig.read())