python|把一个文件下的内容,分成几个文件

import shutil
import os
file_path = '你的绝对路径'
def divide_files(file_path, sub_file_num):#sub_file_num 是 你想要分成几个文件夹
    name = os.listdir(file_path)

    name_num = len(name)
    each_file_num = int(name_num/sub_file_num)

    #我的文件内容是成对的(img,xml)  所以不能出现奇数,以免分到了两个文件夹里面
    if each_file_num//2 != 0:
        each_file_num += 1

    #以下是,创建文件夹 然后把想要复制的内容 复制过来
    for sub_num in range(sub_file_num-1):
        sub_file_path = os.path.join(file_path, str(sub_num)).replace("\\", "/")
        os.mkdir(sub_file_path)

        st=sub_num*each_file_num
        ed=(sub_num+1)*each_file_num
        print(st,ed)
        each_name_list = name[st:ed]

        for each in each_name_list:
            file_p = os.path.join(file_path, each).replace("\\", "/")
            shutil.copy(file_p, sub_file_path)
    #最后一个文件夹:
    sub_file_path = os.path.join(file_path, str(sub_file_num-1)).replace("\\", "/")
    os.mkdir(sub_file_path)
    st = (sub_file_num-1) * each_file_num
    ed = name_num
    print(st,ed)
    each_name_list = name[st:ed]
    for each in each_name_list:
        file_p = os.path.join(file_path, each).replace("\\", "/")
        shutil.copy(file_p, sub_file_path)

i = divide_files(file_path,3)#这边我生成了3个文件夹!

 

你可能感兴趣的:(笔记,脚本,python)