[Tutor] File copying - best way?

Michael P. Reilly arcege@speakeasy.net
Sat, 4 Aug 2001 21:56:50 -0400

On Sat, Aug 04, 2001 at 09:22:05PM -0400, fleet@teachout.org wrote:
> Between
>    os.popen("cp /path1/newfile /path2/oldfile")
> and
>    open("/path1/newfile","w").write(open("/path2/oldfile","r").read())
> Which, if either, is the "preferred" method of copying a file?  The second
> will raise an IOError if it fails.  I have no clue how to test the first.
> Are there other and/or better methods of copying a file?

I am more partial to the copy2() function in the "shutil" module.
It is more like "cp -p" on UNIX.  It is also portable.

Otherwise, I would write it out explicitly:

infile = open("/path2/oldfile", "rb")
outfile = open("/path1/newfile", "wb")
block = infile.read(8192)
while block:
  block = infile.read(8192)

The problem with keeping everything on one line is that a) it is harder
to debug (possibly stepping through code or adding print statements),
and b) it is harder to insert try-except clauses later if you need them.

Also, if the file is large, reading everything at once can be a big
waste of memory (and might even overflow the memory on larger programs).
Reading in chucks is much more efficient.  And unless you know you want
to get lines, always copy in binary.


| Michael P. Reilly                | arcege@speakeasy.net              |