python写的复制粘贴代码

用函数嵌套写的多层文件夹复制粘贴

import os

def copy(old_dir,new_dir):
    docu = os.listdir(old_dir) #获取文件夹中的文件列表
    for file in docu:
        if  os.path.isfile(os.path.join(old_dir,file)): #判断是否是文件还是文件夹,是文件就拷贝到新文件夹中
            with open(os.path.join(old_dir,file),'rb') as stream:
                con = stream.read()
                with open(os.path.join(new_dir,file),'wb') as wstream:
                    wstream.write(con)
        else:#文件夹的话,在目标文件夹中创建文件夹,继续执行函数
            dir1 = os.path.join(new_dir,file)
            os.mkdir(dir1)
            copy(os.path.join(old_dir,file),dir1)



    else:
        print('拷贝完成')
path = r'C:\Users\zoune\PycharmProjects\untitled2\venv\ms'
path1 = r'C:\Users\zoune\PycharmProjects\untitled2\venv\ams'

copy(path,path1)

你可能感兴趣的:(初学之路,python,学习)