按文件名批量分类文件到文件夹

转载  https://blog.csdn.net/lm409/article/details/75452306  略动词}修改

需要:蟒蛇解释器,EXCEL

本方法的分类依据是,遍历某一路径下所有文件和文件夹,找出所有文件。文件名若包含目标文件夹名,则文件会被自动剪切复制到目标文件夹中,否则,不做操作。

import os
import shutil
import pandas as pd

def mkdirs(path):
    path = path.strip() 
    path = path.rstrip("\\") # 去除尾部 \ 符号
    isExists = os.path.exists(path)   
    if not isExists:  
        os.makedirs(path)         # 创建目录
        print(path + ' 创建成功')
        return True
    else:
        print(path + ' 目录已存在')
        return False

'''将原根目录路径下所有子文件移动到新文件夹中,分类依据为文件名称包含文件夹名称'''
def search_file(row_root_path, foldername, new_root_path):
    queue = []
    queue.append(row_root_path)
    while len(queue) > 0:
        tmp = queue.pop(0)
        if (os.path.isdir(tmp)):  #如果该路径是文件夹,遍历该路径中文件和文件夹
            for item in os.listdir(tmp): 
                queue.append(os.path.join(tmp, item))  # 将所得路径加入队列queue
        elif (os.path.isfile(tmp)): #如果该路径是文件,获取文件名和文件目录,将文件名与文件目录连接起来,形成完整路径
            name = os.path.basename(tmp)  
            dirname = os.path.dirname(tmp)  
            row_full_path = os.path.join(dirname, name)  
            new_full_path = new_root_path +'/' + name #定义新路径,匹配符合条件的文件
            if foldername in name:  
                shutil.move(row_full_path, new_full_path)

if __name__ == '__main__':
    data=pd.read_excel('E:/文件批量分类到文件夹.xlsx')
    for i in data['类别文件夹所在路径']:
        mkdirs(i)
    for i in range(len(data['类别'])):
        search_file(data['图片所在路径'][i],data['类别'][i].strip(),data['类别文件夹所在路径'][i])

建立的Excel文件,命名为文件批量分类到文件夹放在E盘如下位置,E:/文件批量分类到文件夹.xlsx,EXCEL形式如下:

猜你喜欢

转载自blog.csdn.net/zhangai8351205/article/details/85381919