Traverse all files in the specified folder and divide them into multiple subfolders in batches according to num (with running code)

Traverse all files in the specified folder and divide them into multiple subfolders in batches by num.

import os
import shutil

file_path = '.\\dataset\\train\\Non-underburning\\'
new_file_path = '.\\Burn\\jpg_video_directory\\Non-underburning\\'

num = 100
list_ = os.listdir(file_path)
if num > len(list_):
    print('num<:', len(list_))
    exit()
if int(len(list_) % num) == 0:
    num_file = int(len(list_) / num)
else:
    num_file = int(len(list_) / num) + 1
cnt = 0
for n in range(1, num_file + 1):
    new_file = os.path.join(new_file_path + str(n))
    if os.path.exists(new_file + str(cnt)):
        print('error', new_file)
        exit()
    print('new:', new_file)
    os.mkdir(new_file)
    list_n = list_[num * cnt:num * (cnt + 1)]
    for m in list_n:
        old_path = os.path.join(file_path, m)
        new_path = os.path.join(new_file, m)
        shutil.copy(old_path, new_path)
    cnt += 1

Guess you like

Origin blog.csdn.net/LZL2020LZL/article/details/128920874