Search code examples
pythonsortingphoto

Sorting Photos by Filename into Folders in Python


I am trying to sort photos located in a folder by their name into folders of the same name.

project/photos_to_sort/
IMG_20200101_001.jpg
IMG_20200101_002.jpg
IMG_20200103_001.jpg
IMG_20200207_001.jpg
IMG_20200207_002.jpg
IMG_20200207_003.jpg

Script should create 3 folders with the names: 20200101, 20200103, 20200207 and then place the photos into the correct folders.

project/sorted/20200101/
IMG_20200101_001.jpg
IMG_20200101_002.jpg
project/sorted/20200103/
IMG_20200103_001.jpg
project/sorted/20200207/
IMG_20200207_001.jpg
IMG_20200207_002.jpg
IMG_20200207_003.jpg

Here is my code so far but I can seem to get this to work:

import os
import shutil


# Input absolute path to PhotoSort program.
os.chdir("C:\\Users\\User\\Projects\\PhotoSort")


for f in os.listdir("photos_to_sort"):
    folderName = f[4:12]

if os.path.exists(folderName):
    shutil.copy(
        os.path.join("C:\\Users\\User\\Projects\\PhotoSort\\", f),
        os.path.join("C:\\Users\\User\\Projects\\PhotoSort\\sorted\\", folderName),
    )
else:
    os.mkdir(folderName)
    shutil.copy(
        os.path.join("C:\\Users\\User\\Projects\\PhotoSort\\", f),
        os.path.join("C:\\Users\\User\\Projects\\PhotoSort\\sorted\\", folderName),
    )

This spits out a FileNotFoundError at the moment.


Solution

  • Your folderName is not a valid path it is just a string you have to create path as sorted/folderName as you have mentioned. And also your photos are in photos_to_sort folder and you are using the root folder.

    And when you are setting your absolute path using a relative path makes things simpler and works on other machines also.

    It is best practice to create path using os.path.join as it creates path according to the underlying operating system so that your script can run both on Windows and Linux/ Unix

    Below is working code

    import os
    import shutil
    
    
    # Input absolute path to PhotoSort program.
    os.chdir("C:\\Users\\User\\Projects\\PhotoSort")
    
    
    for f in os.listdir("photos_to_sort"):
        folderName = f[4:12]
    
        if os.path.exists(os.path.join("sorted", folderName)):
            shutil.copy(
                os.path.join(
                    "photos_to_sort", f),
                os.path.join(
                    "sorted", folderName),
            )
        else:
            os.makedirs(os.path.join(
                "sorted", folderName))
            shutil.copy(
                os.path.join(
                    "photos_to_sort", f),
                os.path.join(
                    "sorted", folderName),
            )