复制文件夹(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循环则不执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值