4
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?

Piotr Dobrogost
  • 41,292
  • 40
  • 236
  • 366
Felix
  • 831
  • 4
  • 12
  • 16

1 Answers1

7

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())
plaes
  • 31,788
  • 11
  • 91
  • 89
  • 1
    **Note:** If you're using Python 2.5 you need to do `from __future__ import with_statement` at the *top* of the file. – mvanveen Feb 24 '12 at 07:37
  • Is the memory freed once the script has concluded? – Felix Feb 24 '12 at 07:56
  • @MonteCarloGenerator: What memory? This example basically reads data from one stream and writes it to another. And after you exit the `with` blocks, the file descriptors for `dest` and `orig` are closed. – plaes Feb 24 '12 at 08:22