Copy file or directories recursively in Python

前端 未结 5 902
无人及你
无人及你 2020-11-27 12:17

Python seems to have functions for copying files (e.g. shutil.copy) and functions for copying directories (e.g. shutil.copytree) but I haven\'t fou

5条回答
  •  Happy的楠姐
    2020-11-27 12:42

    To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)

    import os, shutil
    
    root_src_dir = r'C:\MyMusic'    #Path/Location of the source directory
    root_dst_dir = 'D:MusicBackUp'  #Path to the destination folder
    
    for src_dir, dirs, files in os.walk(root_src_dir):
        dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
        if not os.path.exists(dst_dir):
            os.makedirs(dst_dir)
        for file_ in files:
            src_file = os.path.join(src_dir, file_)
            dst_file = os.path.join(dst_dir, file_)
            if os.path.exists(dst_file):
                os.remove(dst_file)
            shutil.copy(src_file, dst_dir)
    

    Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.

提交回复
热议问题