How do you copy files from one location to another?

Ethan Furman ethan at stoneleaf.us
Fri Jun 17 18:15:41 EDT 2011


John Salerno wrote:
> On Jun 17, 2:23 pm, Terry Reedy <tjre... at udel.edu> wrote:
> 
>> If you follow the second part of Greg's suggestion 'or one of the other
>> related function in the shutil module', you will find copytree()
>> "Recursively copy an entire directory tree rooted at src. "
> 
> Yeah, but shutil.copytree says:
> 
> "The destination directory, named by dst, must not already exist"
> 
> which again brings me back to the original problem. All I'm looking
> for is a simple way to copy files from one location to another,
> overwriting as necessary, but there doesn't seem to be a single
> function that does just that.

If you don't mind deleting what's already there:

shutil.rmtree(...)
shutil.copytree(...)

If you do mind, roll your own (or borrow ;):

8<-------------------------------------------------------------------
#stripped down and modified version from 2.7 shutil (not tested)
def copytree(src, dst):
     names = os.listdir(src)
     if not os.path.exists(dst):  # no error if already exists
         os.makedirs(dst)
     errors = []
     for name in names:
         srcname = os.path.join(src, name)
         dstname = os.path.join(dst, name)
         try:
             if os.path.isdir(srcname):
                 copytree(srcname, dstname, symlinks, ignore)
             else:
                 copy2(srcname, dstname)
         except (IOError, os.error), why:
             errors.append((srcname, dstname, str(why)))
         # catch the Error from the recursive copytree so that we can
         # continue with other files
         except Error, err:
             errors.extend(err.args[0])
     if errors:
         raise Error(errors)
8<-------------------------------------------------------------------

~Ethan~



More information about the Python-list mailing list