Python---复制文件夹

Python从入门到高手(内部资源-配学习资料)_哔哩哔哩_bilibili

import os

# 文件复制
src_path = r'C:\Users\RSB\Desktop\Python文件夹\p1'
target_path = r'C:\Users\RSB\Desktop\Python文件夹\p2'


# 封装成函数
def copy(src, target):
    if os.path.isdir(src) and os.path.isdir(target):
        filelist = os.listdir(src)  # ['','','']
        for file in filelist:  # aa.txt
            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)

---------------------------------------------------------------------------------

import os

# 文件复制
src_path = r'C:\Users\RSB\Desktop\Python文件夹\p1'
target_path = r'C:\Users\RSB\Desktop\Python文件夹\p3'

filelist = os.listdir(src_path)
print(filelist)


def copy(src_path, target_path):
    # 获取文件夹里面内容
    filelist = os.listdir(src_path)
    # 遍历列表
    for file in filelist:
        # 拼接路径
        path = os.path.join(src_path, file)
        tar_path = target_path
        # 判断是文件夹还是文件
        if os.path.isdir(path):
            tar_path = os.path.join(tar_path, file)
            os.mkdir(tar_path)
            # 递归调用copy
            copy(path, tar_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('复制完成!')


# 调用copy
copy(src_path, target_path)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值