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

Fel*_*lix 3 python resources file

from sys import argv
script, origin, destination = argv

open(destination, 'w').write(open(origin).read())
Run Code Online (Sandbox Code Playgroud)

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

pla*_*aes 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())
Run Code Online (Sandbox Code Playgroud)