python按照文件创建日期整理文件至文件夹

# -*- coding: utf-8 -*-
# @Time : 2019-02-15 13:31
# @Author : cxa
# @File : sortbydate.py
# @Software: PyCharm
import glob
import pathlib
import os
import datetime
import traceback
from concurrent import futures
import time
from functools import partial

'''
根据文件创建文件建立文件夹
'''


def to_str_path(path):
    if path:
        new_path = os.fspath(path)
    return new_path


def movefile(image_path, dir_path):
    try:
        file_time = os.path.getctime(image_path)
        stamp_to_datetime = datetime.datetime.fromtimestamp(file_time)
        file_date = datetime.datetime.strftime(stamp_to_datetime, "%Y%m%d")
        date_dir = (dir_path.joinpath(file_date))
        jpg_dir_path, jpg_name = os.path.split(image_path)

        if not os.path.exists(date_dir):
            os.makedirs(to_str_path(date_dir))
            print(f"创建文件夹:{file_date},当前路径是{date_dir}")
        new_file_path = to_str_path(os.path.join(date_dir, jpg_name))
        print(f"开始移动文件{jpg_name},完整路径 {new_file_path}")
        os.rename(image_path, new_file_path)  # 移动文件或重命名,这里是移动文件
        print(f"指定文件已经移动到当前目录的{date_dir}目录")
    except:
        print(traceback.format_exc())


def start(filename: str = None, filetype: str = "jpg"):
    '''

    :param filename: 指定文件夹名,默认当前py文件所在的文件夹
    :param date_str: 删除日期格式yyyymmdd
    :param filetype: 需要删除的文件类型默认jpg.
    :return: None
    '''

    filename = filename or __file__
    dir_path = pathlib.Path(filename).resolve().parent
    image_path_list = glob.glob(to_str_path(dir_path.joinpath(f"*.{filetype}")))
    movef = partial(movefile, dir_path=dir_path)
    with futures.ThreadPoolExecutor(max_workers=10) as pool:
        pool.map(movef, image_path_list)


if __name__ == '__main__':
    start_t = time.time()
    start()
    end = time.time()
    print(end - start_t)

原文地址:https://www.cnblogs.com/c-x-a/p/10383807.html