Python按照不同的后缀把文件存入不同的文件夹下面(后缀分类)

此处以分类六个文件夹为例,代码如下,src是原文件目录,dst1,dst2分别为目标文件夹目录(分类后的文件夹)
以分类”jpg”和”png”图像为例,代码如下:

def split_file(src, dst1, dst2):
    import os
    import shutil
    ''' 函数作用:将不同文件中不同后缀的文件拷贝到不同文件夹 example:区分jpg和png src:str-原文件路径 dst:str-分类后文件路径 '''
    # 区分jpg和png
    jpg = []
    png = []
    for f in os.listdir(src):
        if f.endswith('.jpg'):  # 根据后缀名不同,自己修改
            jpg.append(f)
        elif f.endswith('.png'):  # 根据后缀名不同,自己修改
            png.append(f)
    # 创建目标文件夹
    if not os.path.isdir(dst1):
        os.mkdir(dst1)
    if not os.path.isdir(dst2):
        os.mkdir(dst2)
        
    # 拷贝文件到目标文件夹
    count = 1
    for j in jpg:
        _jpg = os.path.join(src, j)
        shutil.copy(_jpg, dst1)
        print("{}文件已完成{}张jpg图像拷贝".format(src, count))
        count = count+1
    count = 1
    for p in png:
        _png = os.path.join(src, p)
        shutil.copy(_png, dst2)
        print("{}文件已完成{}张png图像拷贝".format(src, count))
        count = count+1
    # 如果需要进行文件重命名,则激活以下函数
    '''

src1 = "D:\\datasets\\SOD\\RGBSalDataset\\ECSSD\\Imgs"
src2 = "D:\\datasets\\SOD\\RGBSalDataset\\HKU-IS\\Imgs"
src3 = "D:\\datasets\\SOD\\RGBSalDataset\\JuddDB\\Imgs"
src4 = "D:\\datasets\\SOD\\RGBSalDataset\\MSRA-10k\\MSRA10K"
src5 = "D:\\datasets\\SOD\\RGBSalDataset\\MSRA-B\\MSRA-B"
src6 = "D:\\datasets\\SOD\\RGBSalDataset\\PASCAL-S\\Imgs"
# contents_list = [src1, src2, src3, src4, src5, src6]
if __name__ == "__main__":
    for i in range(6):
        if i == 0:
            split_file(src1, "D:\\SOD_COD_DataSets\\SOD\\ECSSD\\Imgs", "D:\\SOD_COD_DataSets\\SOD\\ECSSD\\GT")
        elif i == 1:
            split_file(src2, "D:\\SOD_COD_DataSets\\SOD\\HKU-IS\\Imgs", "D:\\SOD_COD_DataSets\\SOD\\HKU-IS\\GT")
        elif i == 2:
            split_file(src3, "D:\\SOD_COD_DataSets\\SOD\\JuddDB\\Imgs", "D:\\SOD_COD_DataSets\\SOD\\JuddDB\\GT")
        elif i == 3:
            split_file(src4, "D:\\SOD_COD_DataSets\\SOD\\MSRA10K\\Imgs", "D:\\SOD_COD_DataSets\\SOD\\MSRA10K\\GT")
        elif i == 4:
            split_file(src5, "D:\\SOD_COD_DataSets\\SOD\\MSRA-B\\Imgs", "D:\\SOD_COD_DataSets\\SOD\\MSRA-B\\GT")
        else:
            split_file(src6, "D:\\SOD_COD_DataSets\\SOD\\PASCAL-S\\Imgs", "D:\\SOD_COD_DataSets\\SOD\\PASCAL-S\\GT")
	print("congratulation!")
    原文作者:I松风水月
    原文地址: https://blog.csdn.net/qq_38683460/article/details/123714162
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞