python递归实现文件复制,通过递归函数将文件夹,子文件夹和文件从一个路径复制到python中的另一个路径...

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)

the copy_files function will copy the files from src +"/"+src_folder to dst+"/"+src_folder

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?

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值