文件自动分类

根据文件类型创建模式,并实现自动分类

# *
# *  @author Zhaoliang Ye 叶昭良(zl_ye@qny.chng.com.cn)
# *  @version V0.1
# *  @Title: autoClassifyDirectory.py
# *  @Description: 按文件类型自动分类  根据文件结尾类型创建模式,并实现自动分类
# *  @Time: 2022/2/11 23:12
# *

import shutil
import os


processDir="d://test1"

imageDir=os.path.join(processDir,"images")
imagePattern=("jpg","png","tif","tmp")
musicDir=os.path.join(processDir,"music")
musicPattern=("mp3","mov")
oaDir=os.path.join(processDir,"oa")
oaPattern=("xlsx","xls","docx","doc","pptx","ppt")
movieDir=os.path.join(processDir,"movie")
moviePattern=("AVI","mp4","flv")

logDir=os.path.join(processDir,"log")
logPattern=("txt","md","log")
def moveFiles(fileWithPath,target):
    """
    :param filename:
    :param pattern: ("jpg","png","tif","tmp") a tuple
    :param target:
    :return:
    """
    if not os.path.exists(target):
        os.mkdir(target)
    shutil.copy2(fileWithPath, target)
    os.remove(fileWithPath)
    print(f'\033[1;34m {fileWithPath} has been moved to {target} \033[0m')


try:
    print(f'\033[1;32m 自动文件分类 \033[0m')
    for filename in os.listdir(processDir):
        # if os.path.isdir(filename):
        #     print(f'\33[1;32m {filename} 是一个文件夹 不分类\033[0m')
        #     continue
        fileWithPath = os.path.join(processDir, filename)
        print(f'filename= {fileWithPath} isfile? = {os.path.isfile(fileWithPath)}')
        if os.path.isfile(fileWithPath):
            if fileWithPath.lower().endswith(imagePattern):
                moveFiles(fileWithPath, imageDir)
            elif fileWithPath.lower().endswith(musicPattern):
                moveFiles(fileWithPath, musicDir)
            elif fileWithPath.lower().endswith(oaPattern):
                moveFiles(fileWithPath, oaDir)
            elif fileWithPath.lower().endswith(moviePattern):
                moveFiles(fileWithPath,   movieDir)
            elif fileWithPath.lower().endswith(logPattern):
                moveFiles(fileWithPath, logDir)
            else:
                print(f'\33[1;32m {fileWithPath} 还没有分好类\033[0m')
                continue
        else:
            print(f'\033[1;31m {filename} is a  directory  \033[0m')
            continue

except OSError:
    print(f'\033[1;31m Error happened try again  \033[0m')

finally:
    os.system("cls" if os.name=="nt" else "clear")

print(f'\033[1;33m 文件自动分类结束 \033[0m')

结果:

   自动文件分类
  filename= d://test1\combined.xlsx isfile? = True
   d://test1\combined.xlsx has been moved to d://test1\oa
  filename= d://test1\images isfile? = False
   images is a  directory
  filename= d://test1\log isfile? = False
   log is a  directory
  filename= d://test1\oa isfile? = False
   oa is a  directory
 文件自动分类结束

  进程已结束,退出代码0
Related
叶昭良
叶昭良
Engineer of offshore wind turbine technique research

My research interests include distributed energy, wind turbine power generation technique , Computational fluid dynamic and programmable matter.