Python --- 文件夹的复制

引入os模块

os.path.dirname(_file_) # 获取当前文件所在的文件目录(绝对路径)
os.path.join(path,'') # 返回一个拼接后的新路径
import os

def copy_file(src, dest):
    # 判断是否是文件夹
    if os.path.isdir(src) and os.path.isdir(dest):
        file_list = os.listdir(src) # 拿到源文件夹里的所有文件
        # 遍历列表
        for file in file_list:
            # 得到全路径
            src_path = os.path.join(src, file)
            # 如果是文件夹 --> 在目标文件夹下新建文件夹然后复制
            if os.path.isdir(src_path):
                # 拿到文件夹的名然后在目标文件夹下新建
                target_path = os.path.join(dest, file)
                os.mkdir(target_path)
                copy_file(src_path, target_path)
            else:
                # 不是文件夹 --> 正常复制
                with open(src_path, 'rb') as rstream:
                    contain = rstream.read()
                    dest_path = os.path.join(dest, file)
                    with open(dest_path, 'wb') as wstream:
                        wstream.write(contain)
        else:
            print("复制完毕!")


src_path = r'F:\file_1'
dest_path = r'F:\file_2'

copy_file(src_path, dest_path)
posted @ 2022-11-06 21:42  来日可追  阅读(428)  评论(0编辑  收藏  举报