So basically, what you want to do is:
- Find every file in a given folder
- Take the first part of each filename and use that as the folder name
- If the folder doesn't exist, create it
- Move the file into that folder
- Repeat
Well, nifty! Figuring out what we want to do is half the battle -- now, it's mostly a matter of googling and turning this into code.
First, we need the folder to check in:
folder_path = "myfolder"
Now, we want to find every file inside that folder. A quick googling session turns up this:
import os
import os.path
images = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
As an aside, I'm going to be using os.path.join
a fair bit, so you may want to briefly read up on what it does. The guide you linked to in the comments covers it fairly well.
Now, we want the first part of each name. I'm going to assume that we'll treat everything up the first dash as the folder name, and ignore the rest. One way to do that is to use string.split
, which splits a string by the given character into a list of strings, and grab the first element:
for image in images:
folder_name = image.split('-')[0]
Now, if that folder doesn't already exist, we want to create it. Again, google is our friend:
new_path = os.path.join(folder_path, folder_name)
if not os.path.exists(new_path):
os.makedirs(new_path)
And finally, we move the original image:
import shutil
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)
Putting it all together:
import os
import os.path
import 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)