pythoncopycopytree

How to copy all files including subfolders using Python


i have tried many possibilities i have found on the net so far and i just can not get it working. I have this code:

def copytree(src, dst, symlinks=False, ignore=None):
    if not os.path.exists(dst):
        os.makedirs(dst)
    for item in os.listdir(src):
        s = str(os.path.join(src, item))
        d = str(os.path.join(dst, item))
        if os.path.isdir(s):
            copytree(s, d, symlinks, ignore)
        else:
            if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
                shutil.copy2(s, d)

Using this code i can copy all files from one source folder into a new destination folder. But this always fails if there are subfolders in the source folder. The code is already checking wether the item to be copied is a folder or a single file, so where is the problem with this code?


Solution

  • To achieve this you will want to use import os and import shutil.

    Refer to this as an example:

    import os
    import shutil
    
    for root, dirs, files in os.walk('.'):
       for file in files:
          path_file = os.path.join(root,file)
          shutil.copy2(path_file,'destination_directory')