Copying Files

Peter Hansen peter at engcorp.com
Fri Jun 6 23:51:51 EDT 2003


Stan Cook wrote:
> 
> Can someone give me a clue on using the copyfile function?  I've tried
> implementing it in this fashion without success.
> 
> copyfile(d:\work\temp.dbf, d:\w)

Assuming you mean the one in the shutil module, you have to give
it strings.  In Python, string parameters are always enclosed
in quotation marks.  (Did you do the tutorial? ... this sort of
thing would probably be clearer if you had.)

Try this instead:

import shutil
shutil.copyfile('c:/work/temp.dbf', 'd:/w')

Note the following points too:

1. d:/w is presumably an actual filename, not a folder name.  It
   appears copyfile() must have a *file* as its destination, not
   merely a folder (probably as documented, if you RTFM :-).

2. It's generally easier and more readable to use the forward
   slash in paths.  They work fine in most cases even on Windows.
   (Not all, unfortunately, but most.)  If you want to use
   backslashes, you should *always* escape the backslash as in:

      copyfile('c:\\work\\temp.dbf', 'd:\\w')

   or use "raw" strings like this:

      copyright(r'c:\work\temp.dbf', r'd:\w')

   It's up to you to decide which is more readable, but few find the
   \\ approach to be the best one.

   The reason you need to use the r'' approach is that the backslash
   introduces "escape sequences" for special characters in Python 
   strings, such as '\n' for ASCII 13 (Carriage Return), '\t' for 
   ASCII 8 (Horizontal Tab), and so forth.  Your filename would 
   contain an (invalid) TAB character the way you wrote it, not a "t".

-Peter




More information about the Python-list mailing list