您当前的位置: 首页 >  Python

Xavier Jiezou

暂无认证

  • 0浏览

    0关注

    394博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Python】多线程实现批量文件移动(带进度条)

Xavier Jiezou 发布时间:2021-05-12 13:52:54 ,浏览量:0

引言

编写Python脚本实现将一个文件夹中的所有文件按照修改日期(xxxx年xx月xx日)分类移动。

依赖
pip install alive_progress 
代码
import os
import time
import shutil
import concurrent.futures as cf
from alive_progress import alive_bar  # pip install alive_progress


def main():
    name_list = os.listdir()
    name_list.remove(os.path.basename(__file__))
    with alive_bar(len(name_list)) as bar: # 进度条
        with cf.ThreadPoolExecutor() as p: # 线程池
            for name in name_list:
                time_stamp = os.path.getmtime(name) # 获取文件修改日期时间戳
                time_local = time.localtime(time_stamp) # 将时间戳转换为本地时间
                time_style = time.strftime(r'%Y%m%d', time_local) # 将本地时间转换为指定格式的时间
                os.makedirs(time_style, exist_ok=True)
                p.submit(shutil.move, name, time_style).add_done_callback(lambda func: bar())


if __name__ == '__main__':
    main()
提示

这里进度条打印用的是alive_progress库,用tqdm库也可以,代码改一下:

import os
import time
import shutil
from tqdm import tqdm # pip install tqdm
import concurrent.futures as cf


def main():
    name_list = os.listdir()
    name_list.remove(os.path.basename(__file__))
    with tqdm(total=len(name_list)) as bar: # 进度条
        with cf.ThreadPoolExecutor() as p: # 线程池
            for name in name_list:
                time_stamp = os.path.getmtime(name) # 获取文件修改日期时间戳
                time_local = time.localtime(time_stamp) # 将时间戳转换为本地时间
                time_style = time.strftime(r'%Y%m%d', time_local) # 将本地时间转换为指定格式的时间
                os.makedirs(time_style, exist_ok=True)
                p.submit(shutil.move, name, time_style).add_done_callback(lambda func: bar.update())


if __name__ == '__main__':
    main()

个人觉得tqdm进度条不如alive_progress好看和详细,对比如下:

  • tqdm 在这里插入图片描述
  • alive_progress 在这里插入图片描述
参考

https://docs.python.org/zh-cn/3.11/library/concurrent.futures.html

关注
打赏
1661408149
查看更多评论
立即登录/注册

微信扫码登录

0.0446s