Skip to content Skip to sidebar Skip to footer

Copy Folder, Subfolders And Files From A Path To Another Path In Python Via A Recursive Function

I want to copy some folders and files from a path to another path. for example, I want to copy the folder(called folder1) which has some other subfolders and some files inside itse

Solution 1:

Use os.path.isdir instead of os.path.exists to ensure that it can only be a directory not a file. And os.path.join is better than concatenating path strings by ourselves.

def CopyFol_Subfolders(src, dst):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            CopyFol_Subfolders(s, d)
        else:
            shutil.copy2(s, d)

Post a Comment for "Copy Folder, Subfolders And Files From A Path To Another Path In Python Via A Recursive Function"