Article directory
Preamble
When there are too many texts or folders in our computer, and sometimes we want to find the file we want, we can only search for the file name. Search by name, but only more files will be found by searching, and this is only in the case of many files.
What if the file names are basically the same, only the serial numbers are different? I'm so blind, I guess I haven't found it yet.
Then we can use Python to automatically classify files in batches and save them to folders. When looking for them next time, we can easily find them.
Here we take more than two hundred original world files as an example
Code display
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)
Show results
Here we take classification by month as an example, and automatically create folders for classification.
Look, it's much easier to find,
brothers, go try it