【Python】多线程实现批量文件移动

引言

编写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()

参考

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

上一篇:git recommend(alive)


下一篇:2021.4.1 字节-飞书-测开一面