【问题标题】:Splitting content from a single folder to multiple sub folders using Python使用 Python 将内容从单个文件夹拆分到多个子文件夹
【发布时间】:2019-01-18 11:24:01
【问题描述】:

在我的文件中,我有大量 jpg 格式的图像,它们被命名为 [fruit type].[index].jpg
不是手动创建三个新的子文件夹来将图像复制并粘贴到每个子文件夹中,是否有一些 python 代码可以解析图像的名称并根据名称中的fruit type 选择将图像重定向到的位置,同时在解析新的fruit type时新建一个子文件夹?


之前

  • 训练集(文件)
    • apple.100.jpg
    • apple.101.jpg
    • apple.102.jpg
    • apple.103.jpg
    • peach.100.jpg
    • peach.101.jpg
    • peach.102.jpg
    • orange.100.jpg
    • orange.101.jpg

之后

  • 训练集(文件)
    • 苹果(文件)
      • apple.100.jpg
      • apple.101.jpg
      • apple.102.jpg
      • apple.103.jpg
    • 桃子(文件)
      • peach.100.jpg
      • peach.101.jpg
      • peach.102.jpg
    • 橙色(文件)
      • orange.100.jpg
      • orange.101.jpg

【问题讨论】:

    标签: python directory


    【解决方案1】:

    这是执行此操作的代码,如果您需要帮助将其合并到您的代码库中,请告诉我:

    import os, os.path, shutil
    
    folder_path = "test"
    
    images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
    
    for image in images:
        folder_name = image.split('.')[0]
    
        new_path = os.path.join(folder_path, folder_name)
        if not os.path.exists(new_path):
            os.makedirs(new_path)
    
        old_image_path = os.path.join(folder_path, image)
        new_image_path = os.path.join(new_path, image)
        shutil.move(old_image_path, new_image_path)
    

    【讨论】:

      【解决方案2】:

      如果它们的格式都与您给出的三个水果示例类似,您可以简单地对遇到的每个文件名执行 string.split(".")[0]:

      import os
      
      for image in images:
          fruit = image.split(".")[0]
          if not os.path.isdir(fruit):
              os.mkdir(fruit)
          os.rename(os.path.join(fruit, image))
      

      【讨论】:

        猜你喜欢
        • 2022-11-04
        • 1970-01-01
        • 2018-05-29
        • 2022-07-17
        • 2021-05-17
        • 1970-01-01
        • 2017-05-20
        • 2020-09-05
        • 1970-01-01
        相关资源
        最近更新 更多