Skip to content Skip to sidebar Skip to footer

How Do I Close A File Object I Never Assigned To A Variable?

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 somet

Solution 1:

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())

Post a Comment for "How Do I Close A File Object I Never Assigned To A Variable?"