Search code examples
pythoncopy-pasteshutil

How to copy both folder and files in python


I am aware that using
shutil.copy(src,dst) copies files and
shutil.copytree(src,dst) is used for copying directories.

Is there any way so I don't have to differentiate between copying folders and copying files?

Tysm


Solution

  • You might want to take a look to this topic, where the same question was answered.

    https://stackoverflow.com/a/1994840/17595642

    Functions can be written to do so.

    Here is the one implemented in the other topic :

    import shutil, errno
    
    def copyanything(src, dst):
        try:
            shutil.copytree(src, dst)
        except OSError as exc: # python >2.5
            if exc.errno in (errno.ENOTDIR, errno.EINVAL):
                shutil.copy(src, dst)
            else: raise