Python - Move and overwrite files and folders

后端 未结 6 2010
情话喂你
情话喂你 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:03

    If you also need to overwrite files with read only flag use this:

    def copyDirTree(root_src_dir,root_dst_dir):
    """
    Copy directory tree. Overwrites also read only files.
    :param root_src_dir: source directory
    :param root_dst_dir:  destination 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):
                try:
                    os.remove(dst_file)
                except PermissionError as exc:
                    os.chmod(dst_file, stat.S_IWUSR)
                    os.remove(dst_file)
    
            shutil.copy(src_file, dst_dir)
    

提交回复
热议问题