2020年1月5日星期日

Python: divide a folder into small folders

Assume that there are 10,000 pictures in a large folder. This code is used to divide the 10,000 pictures into 9 subfolders according to the characteristics of the file name:

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



The advantage of this is that for any unfamiliar test.py file, you can quickly start multiple test tasks in a short time without changing the test code, which is equivalent to manual parallel processing.

 # _*_ 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)

没有评论:

发表评论