通过递归函数将文件夹,子文件夹和文件从一个路径复制到python中的另一个路径 [英] copy folder, subfolders and files from a path to another path in python via a recursive function

查看:267
本文介绍了通过递归函数将文件夹,子文件夹和文件从一个路径复制到python中的另一个路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将某些文件夹和文件从一个路径复制到另一个路径。例如,我想将文件夹(称为folder1)复制到另一个文件夹(dst),该文件夹具有一些其他子文件夹和其内部的某些文件。在我的程序中,首先,我要检查目标文件夹中是否存在名为folder1的文件夹,如果没有,请创建一个具有folder1名称的文件夹,然后将folder1的内容复制到目标。另外,也许我们在目标路径中有folder1,但是目标中不存在folder1的一些子文件夹,因此我们必须使用递归函数。为此,这是我的递归函数:

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 itself to another folder(dst). In my program, at the first, I want to check if there is a folder named folder1 in destination folder and if not, create a folder with folder1 name and then copy the content of folder1 to target. In addition, maybe we have folder1 in the target path, but there are some subfolders of folder1 which don't exist in target and we must use a recursive function for that. Here is my recursive function for this purpose:

def CopyFol_Subfolders(src, src_folder, dst):
    Dir = next(os.walk(src))[1]
    sub_files = ""
    sub_files = next(os.walk(src))[2]
    if not os.path.exists(dst + "/" + src_folder):
        os.makedirs(dst + "/" + src_folder)
        shutil.copy2(src + "/" + src_folder, dst + "/" + src_folder)

    elif os.path.exists(src + "/" + src_folder) and is_exist_file(src+"/"+src_folder,dst+"/"+src_folder,sub_files):
        copy_files(sub_files, src+"/"+src_folder, dst+"/"+src_folder)
    else:
        subfolders = ""
        subfolders = next(os.walk(src + "/" + src_folder+"/"))[1]
        for folder in subfolders:
            CopyFol_Subfolders(src + "/" + src_folder, folder, dst + "/" + src_folder)

copy_files 函数将从 src + / + src_folder复制文件 dst + / + sr c_folder

我很困惑,这不起作用。我在 shutil.copy2 中遇到了不同的错误,告诉我 x不是文件 x是一个目录
能否请我检查一下递归函数的逻辑,让我知道这是什么问题?

I be confused and this does not work. I got different errors in shutil.copy2 which tell me x is not a file or x is a directory. Can please some one check logic of my recursive function and let me know what is this problem?

推荐答案

使用 os.path.isdir 而不是 os.path.exists 来确保它只能是目录而不是文件。而且 os.path.join 比我们自己连接路径字符串更好。

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)

这篇关于通过递归函数将文件夹,子文件夹和文件从一个路径复制到python中的另一个路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆