Search code examples
pythoncopy

A function to copy folder along with its contents python


Is there a function that copies a parent folder along with all its content to a specified destination ?

I have used different functions but they seem to copy the contents excluding the parent folder.


Solution

  • shutil.copytree comes to mind immediately, but your issue is that copying directory foo in bar doesn't create bar/foo.

    My proposal:

    import shutil,os
    
    def copytree2(source,dest):
        os.mkdir(dest)
        dest_dir = os.path.join(dest,os.path.basename(source))
        shutil.copytree(source,dest_dir)
    
    • first create destination
    • then generate destination dir, which is the destination added source basename
    • perform copytree with the new destination, so source folder name level appears under dest

    There's no subtle check about dest directory already exist or whatnot. I'll let you add that if needed (using os.path.isdir(dest) for instance)

    Note that functions from shutil come with a note which encourages users to copy and modify them to better suit their needs.