pythonpython-2.7

how to copy directory with all file from c:\\xxx\yyy to c:\\zzz\ in python


I've been trying to use "copytree(src,dst)", however I couldn't since the destination folder should exists at all.Here you can see the small piece of code I wrote:

def copy_dir(src,dest):
    import shutil
    shutil.copytree(src,dest)

copy_dir('C:/crap/chrome/','C:/test/') 

and this is the error I m getting as I expected...

Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\workspace\MMS-Auto\copy.py", line 5, in        <module>
copy_dir('C:/crap/chrome/','C:/test/')   
File "C:\Documents and Settings\Administrator\workspace\MMS-Auto\copy.py", line 3, in copy_dir
shutil.copytree(src,dest)
File "C:\Python27\lib\shutil.py", line 174, in copytree
os.makedirs(dst)
File "C:\Python27\lib\os.py", line 157, in makedirs
mkdir(name, mode)
WindowsError: [Error 183] Cannot create a file when that file already exists:    'C:/test/'

Here is my question is there a way I could achieve the same result without creating my own copytree function?

Thank you in advance.


Solution

  • Look at errno for possible errors. You can use .copytree() first, and then when there is error, use shutil.copy.

    From: http://docs.python.org/library/shutil.html#shutil.copytree

    If exception(s) occur, an Error is raised with a list of reasons.

    So then you can decide what to do with it and implement your code to handle it.

    import shutil, errno
    
    def copyFile(src, dst):
        try:
            shutil.copytree(src, dst)
        # Depend what you need here to catch the problem
        except OSError as exc: 
            # File already exist
            if exc.errno == errno.EEXIST:
                shutil.copy(src, dst)
            # The dirtory does not exist
            if exc.errno == errno.ENOENT:
                shutil.copy(src, dst)
            else:
                raise
    

    About .copy(): http://docs.python.org/library/shutil.html#shutil.copy

    Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings.

    Edit: Maybe also look into distutils.dir_util.copy_tree