file – I need to write a Python script to sort pictures, how would I do this?

file – I need to write a Python script to sort pictures, how would I do this?

So basically, what you want to do is:

  1. Find every file in a given folder
  2. Take the first part of each filename and use that as the folder name
  3. If the folder doesnt exist, create it
  4. Move the file into that folder
  5. Repeat

Well, nifty! Figuring out what we want to do is half the battle — now, its 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, Im 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. Im going to assume that well 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 doesnt 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)

file – I need to write a Python script to sort pictures, how would I do this?

Leave a Reply

Your email address will not be published.