python多线程复制文件到一个文件夹 显示进度

模块导入

from progress.bar import IncrementalBar
from concurrent.futures import ThreadPoolExecutor, as_completed

from pathlib import Path
from shutil import copyfile

通用模块:分别是进度条模块 线程池模块 等待线程完成模块
任务相关模块:对文件路径进行操模块 复制文件模块

程序调用

root=r'X:\test'
arg_list=[i for i in get_files(path=root,simple=True,file_top=True)]
cf=copyfile_mutilthread(root)
ret_list=cf.start(arg_list)
# for i in arg_list:
#     cf.file_addsize((1,i))

输入文件夹路径复制文件夹下的直接文件 到目录下out文件夹下 (内部有判断out文件夹是否存在的语句但偶尔报错 怀疑是多线程导致)
get_files 用户函数 用于获取目录下的直接文件 可能存在子目录下文件不获取
arg_list内容如下:

['C:\Users\xxx\Videos\a.mp3', 'C:\Users\xxx\Videos\a.mp4', 'C:\Users\xxx\Videos\a.wav']

ret_list的内容

['C:\Users\xxx\Videos\out\a.mp3', 'C:\Users\xxx\Videos\out\a.mp4', 'C:\Users\xxx\Videos\out\a.wav']

代码可分为两部分 多线程处理 将多次执行的函数
封装成一个类方便数据传递 也可以将参数列表中每个参数封装传递一个字典或列表
完整代码 需完成get_files的功能

点击查看代码
from progress.bar import IncrementalBar
from concurrent.futures import ThreadPoolExecutor, as_completed

from pathlib import Path
from shutil import copyfile


class copyfile_mutilthread:
    root=''
    pool_size=8
    def __init__(self,root) -> None:
        self.root=root
        

    def start(self,arg_list):
        return self.mutil_thread(arg_list=arg_list,func=self.file_addsize)

    def file_addsize(self,arg):
        index,file=arg
        path_file=Path(file)
        root_file=Path(self.root)
        if path_file.is_file():
            size=os.path.getsize(path_file)/1024
            new_name=root_file.joinpath('out',str(size)+' '+path_file.name)
            if not new_name.parent.exists():
                os.makedirs(new_name.parent)
            if new_name.exists():
                os.remove(new_name)
            copyfile(path_file,new_name)
        return (index,str(new_name))

    def mutil_thread(self,arg_list,func):
        print('将工作于多线程下')
        ret_list={}
        task_list=[]
        suffix = '%(percent)d%% [%(index)d/%(max)d in %(elapsed)ds (eta:%(eta_td)s)]'
        
        p= ThreadPoolExecutor(max_workers=self.pool_size) 
        # 添加任务
        for index,i in enumerate(arg_list):
            task_list.append(p.submit(func, (index,i)))  
        # 等待任务wancheng
        with IncrementalBar("等待进度:", max=len(arg_list), suffix=suffix) as bar:
            for task in as_completed(task_list):
                if task.done():
                    index,ret_i= task.result()
                    ret_list[index]=ret_i
                    bar.next()
        # 返回排序好的任务
        items=sorted(ret_list.items())
        ret=[i[1] for i in items]
        return ret
root=r'C:\Users\xin\Videos'
arg_list=[i for i in get_files(path=root,simple=True,file_top=True)]
# ['C:\\Users\\xxx\\Videos\\out\\a.mp3', 'C:\\Users\\xxx\\Videos\\out\\a.mp4', 'C:\\Users\\xxx\\Videos\\out\\a.wav']
cf=copyfile_mutilthread(root)
ret_list=cf.start(arg_list)
# for i in arg_list:
#     cf.file_addsize((1,i))
posted @   caiusxin  阅读(597)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css
点击右上角即可分享
微信分享提示