from sys import argv
script, origin, destination = argv
open(destination, 'w').write(open(origin).read())
如何关闭目标和源文件对象?或者这是我不需要担心的事情?
最佳答案
在简单明了的脚本中,您不必担心这些问题,但在较大的程序中,您可能会用完文件描述符。
从 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())
关于python - 如何关闭从未分配给变量的文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9426978/