繁体   English   中英

如何使用图像名称python分隔文件夹中的图像?

[英]how to separate the images in folder using image name python?

我需要将文件夹中的图像与其在 python 中的文件名分开。 例如,我有一个名为 0_source.jpg、0_main.jpg、0_cell.jpg、1_net.jpg、1_cells.jpg、2_image.jpg、2_name.jpg 的图像文件夹

我想将这些图像分开并保存在不同的文件夹中,例如:folder1:

0_source.jpg, 0_main.jpg, 0_cell.jpg

文件夹2:

1_net.jpg, 1_cells.jpg

文件夹3:

2_image.jpg, 2_name.jpg

我试着环顾四周,但似乎没有一个适合我真正需要的。 希望这里有人可以提供帮助。 我愿意接受任何想法、建议和建议,谢谢。

主要思想是使用正则表达式从图像名称开始提取文件夹名称。 然后构建文件夹并移动图像

import shutil
import re
import os

images = ["0_source.jpg", "0_main.jpg", "0_cell.jpg", "1_net.jpg", "1_cells.jpg", "2_image.jpg", "2_name.jpg"]

def build_images_folders(image_names: [str]):
    folder_name_regex = re.compile(r"^(\d)._*") # Regular expression which extract the folder starting from the image_name name

    for image_name in image_names:
        regex_match = folder_name_regex.match(image_name)
        if regex_match:
            folder_index = regex_match.group(1) # Extract the folder name
            folder_name = "{folder_prefix}{folder_index}".format(folder_prefix="folder_", folder_index=folder_index) # Build the folder name
            os.makedirs(folder_name, exist_ok=True) # Build the folder. If already exists, don't raise exception

            src_image_path = image_name
            dst_image_path = os.path.join(folder_name, image_name)
            shutil.move(src_image_path, dst_image_path)

        else:
            error = "Invalid image name format \"{image_name}\". Expecting <number>_<string>".format(image_name=image_name)
            raise ValueError(error)

if __name__ == '__main__':
    build_images_folders(images

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM