Questions
Questions

Reputation: 137

Splitting content from a single folder to multiple sub folders using Python

In my file, I have a large number of images in jpg format and they are named [fruit type].[index].jpg.
Instead of manually making three new sub folders to copy and paste the images into each sub folder, is there some python code that can parse through the name of the images and choose where to redirect the image to based on the fruit type in the name, at the same time create a new sub folder when a new fruit type is parsed?


Before


After

Upvotes: 3

Views: 17298

Answers (3)

Blue's
Blue's

Reputation: 1

As an idea, hope it helps

   import os
   from pathlib import Path
   import shutil

   folder_path = "images/"
   nameList=[]
   for image in os.listdir(folder_paths):
     folder_name = image.split('.')[0]
     nameList.append(folder_name)
    
   for f in os.listdir(folder_paths):
     Path(folder_name).mkdir(parents=True, exist_ok=True,mode=0o755)
     des = folder_name +"/"+str(f)
     old_path = folder_paths+str(f)
     for path in nameList:
        if f.endswith('.jpg'):
                print(f)
                if path == folder_name:
                  shutil.move(old_path, str(des))
                

Upvotes: 0

joe hoeller
joe hoeller

Reputation: 1277

Here’s the code to do just that, if you need help merging this into your codebase let me know:

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)

Upvotes: 10

solvador
solvador

Reputation: 95

If they are all formatted similarly to the three fruit example you gave, you can simply do a string.split(".")[0] on each filename you encounter:

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))

Upvotes: 0

Related Questions