复制文件夹(python中os模块应用)

1、文件夹中不含文件夹

import os
#一个文件里面含多个文件(不含文件夹)
src_path = r'c:\p1'
target_path = r'c:\p2'

#封装成函数
def copy(src,target):
    if os.path.isdir(src) and os.path.isdir(target):
        filelist = os.listdir(src)
        for file in filelist:

            path = os.path.join(src,file)
            with open(path,'rb') as rstream:
                container = rstream.read()

                path1 = os.path.join(target,file)
                with open(path1,'wb') as wstream:
                    wstream.write(container)
    else:
        print("复制完毕")

#调用函数
copy(src_path,target_path)

2、文件夹中含文件夹(通用)

import os
#一个文件里面含多个文件(含文件夹)
src_path = r'c:\p1'
target_path = r'c:\p2'

def copy(src_path,target_path):
    #获取文件夹里面的内容
    filelist = os.listdir(src_path)
    #文件列表
    for file in filelist:
        #拼接路径
        path = os.path.join(src_path,file)
        #判断是文件夹还是文件
        if os.path.isdir(path):
            #递归调用copy
            copy(path,target_path)
        else:
            #不是文件夹则直接进行复制
            with open(path,'rb') as rstream:
                container = rstream.read()

                path1 = os.path.join(target_path,file)
                with open(path1,'wb') as wstream:
                    wstream.write(container)
    else:
        print('复制完成')

3、补充

for else语法在python是存在的,如果for循环正常结束,else中语句执行。如果break跳出for循环则不执行。
发布了84 篇原创文章 · 获赞 36 · 访问量 4553

猜你喜欢

转载自blog.csdn.net/qq_41475583/article/details/104911195
今日推荐