Python: 将文件夹划分为数个小文件夹

假设大文件夹下有10000张图片,本代码用于将这10000张图片按照文件名的特点,划分到9个子文件夹内:

参考链接:https://www.computationalimaging.cn/2020/01/python-divide-folder-into-small-folders.html

dir_sum    
    --dir1
    --dir2
    ...
    --dir9

这样做的好处是对任何一个不熟悉的test.py文件,可以不改test的代码即可在短时间内快速开始多个测试任务,相当于手动的并行处理。

# _*_ encoding:utf-8 _*_
import os
import sys
from shutil import copyfile


origin_path = './dir_sum/'       # the directory where the target files are located

filelist = os.listdir(origin_path)

for image_index in range(len(filelist)):
    fileName = filelist[image_index] # '1.png'
    fileClass = str(fileName[0]) # The first letter of the file name, including '1', '2', '3', '4', '5', '6', '7', '8', '9'
    filePath = origin_path + fileClass + '/' # The path to which the file should be assigned
    src_fileName = origin_path + fileName
    tar_fileName = filePath + fileName
    if not os.path.exists(filePath):
        os.makedirs(filePath)
    copyfile(src_fileName,tar_fileName)
发布了47 篇原创文章 · 获赞 11 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qazwsxrx/article/details/103756281