Python自动化办公:批量将文件按分类保存,文件再多,只需一秒钟解决

x33g5p2x  于2022-04-23 转载在 Python  
字(1.2k)|赞(0)|评价(0)|浏览(287)

序言

当我们电脑里面的文本或者或者文件夹太多了,有时候想找到自己想要的文件,只能通过去搜索文件名,要是名字忘记了的话,那你也搜不了吧,当然你可通过后缀名去搜索,但是通过搜索出来的文件只会更多,这还只是文件多的情况下。

如果文件名字基本一样,只有序号不一样呢?那特么眼睛看瞎了估计还没找到。

那么我们可以用Python来对文件进行批量自动分类保存到文件夹,下次找的时候,就很轻松的能够找到了。

我们这里以这两百多个world原始文件为例

代码展示

import os
import time
import datetime
import pprint
import shutil
import re

origin_dir = '原始文件/'
target_dir = '目标文件/'
files = os.listdir(origin_dir)

month_compile = re.compile('(20\d\d)([01][0-9])')
print(files)
file_dict = {}
for file in files:
    if file.endswith('.docx'):
        word_file = os.path.join(origin_dir, file)
        month = month_compile.search(word_file)
        if month:
            month = month.groups()
            # print(month.groups())
            if month[-1] == '00':
                month = re.search('(20\d\d)0([01][0-9])', word_file).groups()
            t1 = '-'.join(month)
            if t1 in file_dict.keys():
                file_dict[t1].append(word_file)
            else:
                file_dict[t1] = [word_file]

pprint.pprint(file_dict)

if not os.path.exists(target_dir):
    os.mkdir(target_dir)
# 移动文件
for key in file_dict.keys():
    # 创建文件的月份
    new_file_dir = os.path.join(target_dir, key)
    if not os.path.exists(new_file_dir):
        os.mkdir(new_file_dir)
    for file in file_dict[key]:
        # 获取文件名
        new_file_name = os.path.basename(file)
        # 合并新的文件路径
        new_file_path = os.path.join(new_file_dir, new_file_name)
        print(new_file_name)
        shutil.copyfile(file, new_file_path)

效果展示

我们这里以按月份分类为例,自动创建文件夹进行分类。

看,这不就好找多了

兄弟们,快去试试吧

相关文章