Python - Move and overwrite files and folders

后端 未结 6 1968
情话喂你
情话喂你 2021-01-30 06:27

I have a directory, \'Dst Directory\', which has files and folders in it and I have \'src Directory\' which also has files and folders in it. What I want to do is move the conte

6条回答
  •  余生分开走
    2021-01-30 07:09

    This will go through the source directory, create any directories that do not already exist in destination directory, and move files from source to the destination directory:

    import os
    import shutil
    
    root_src_dir = 'Src Directory\\'
    root_dst_dir = 'Dst Directory\\'
    
    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):
                # in case of the src and dst are the same file
                if os.path.samefile(src_file, dst_file):
                    continue
                os.remove(dst_file)
            shutil.move(src_file, dst_dir)
    

    Any pre-existing files will be removed first (via os.remove) before being replace by the corresponding source file. Any files or directories that already exist in the destination but not in the source will remain untouched.

提交回复
热议问题