How do I close a file object I never assigned to a

2019-07-01 12:44发布

from sys import argv
script, origin, destination = argv

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

How do I close the destination and origin file objects? Or is this something I don't need to worry about?

1条回答
疯言疯语
2楼-- · 2019-07-01 13:31

In short straightforward scripts you shouldn't worry about these issues, but in bigger programs you might run out of file descriptors.

Since version 2.5, Python has with statement, which can do the file closing for you:

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())
查看更多
登录 后发表回答