Copy a file in python

Erik Max Francis max at alcyone.com
Wed Dec 4 17:50:12 EST 2002


Mikael Olofsson wrote:

> But to be honest, I would rather write this as
> 
> open(targetPath,'w').write(open(originalPath,'r').read())

The problem here is that you're relying on the objects going out of
scope or them to be destroyed.  You're really not given any guarantees
on the timeliness in which __del__ destructors will be called, and so it
could be some time before they're actually invoked and the files are
actually closed.  Meanwhile, they're eating up file descriptors or
similar resources in your system, which could potentially bite you in
some certain circumstances on some implementations of Python.

For circumstances in which critical resources are used, explicitly
reclaiming them is a better idea.  So your original form, followed by
calling the .close methods on both file objects, is probably a better
approach.

In my opinion, it's a far better approach to rely on destructor __del__
methods getting called as a safety net, rather than relying on them for
critical resources to get reclaimed in a timely manner.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The little I know, I owe to my ignorance.
\__/ Sacha Guitry
    Polly Wanna Cracka? / http://www.pollywannacracka.com/
 The Internet resource for interracial relationships.



More information about the Python-list mailing list