Python: Moving files to folder based on filenames

12,569

You can use os.path.exists() to check if the folder exists, if it exists copy the jpg into it.

Side note: It's better to use copy. When you use move you can mix everything up if you do something wrong.

import os
import shutil

os.chdir("<abs path to desktop>")

for f in os.listdir("folder"):
    folder_name = f[-6:-4]
    
    if not os.path.exists(folder_name):
        os.mkdir(folder_name)
        shutil.copy(os.path.join("folder", f), folder_name)
    else:
        shutil.copy(os.path.join("folder", f), folder_name)

example

Share:
12,569
ZenB883
Author by

ZenB883

I am a self-taught python programmer and I love coding python to make basic scripts like calculators and aspired to one day become a data analyst. I've been learning how to code using python for the past year and still new to python. I look forward in learning more with the help of veteran and senior python coders here in stackoverflow. I am interested in the areas of Data Science, Artificial Intelligence, Machine-learning, Deep-learning and I hope to learn more as I progress.

Updated on June 04, 2022

Comments

  • ZenB883
    ZenB883 almost 2 years

    I have a folder with 10 images that I wish to move into a new folder based on it's current filenames. I've successfully been able to move every images in the folder into a new folder, and as of now I've been successful at moving each image filename to its own folder but I've yet to figure out how to move all images with the same filename into one folder and the other to another folder. For example below I want to move the images accordingly.

    • 1600_01.jpg ---> folder 1
    • 1700_01.jpg ---> folder 1
    • 1800_02.jpg ---> folder 2
    • 1900_02.jpg ---> folder 2
    • 2000_03.jpg ---> folder 3
    • 2100_03.jpg ---> folder 3

    This is my code thus far for moving the image files to a new folder by creating new folders based on it's filename. I got the part on making folders but I'm quite confused when it created separate image folders for all the images.

    import os, shutil, glob
    
    #Source file 
    sourcefile = 'Desktop/00/'
    
    # for loop then I split the names of the image then making new folder 
    for file_path in glob.glob(os.path.join(sourcefile, '*.jpg*')):
        new_dir = file_path.rsplit('.', 1)[0]    
        # If folder does not exist try making new one
        try:
            os.mkdir(os.path.join(sourcefile, new_dir))
        # except error then pass
        except WindowsError:
            pass
        # Move the images from file to new folder based on image name
        shutil.move(file_path, os.path.join(new_dir, os.path.basename(file_path)))
    

    This is what I got after I ran my script. This is what I got after I ran my script

    However, What I'm trying to do is shown in this image below: Goal

  • ZenB883
    ZenB883 about 6 years
    Thanks for answering my question, however when I ran your script, nothing happened.
  • BcK
    BcK about 6 years
    Put the script and the folder inside the same directory, I had tried it with txt files and it works.
  • ZenB883
    ZenB883 about 6 years
    hey could you check my codes if i'm missing anything because I feel like i'm missing 1 more ingredient to this script and I can't figure out which, what am I missing?
  • BcK
    BcK about 6 years
    You need to give me more info about what is happening on your side, added image for proof.
  • ZenB883
    ZenB883 about 6 years
    Yes, It works but the path that it was copied to was desktop and the error is FileNotFoundError: [WinError 3] The system cannot find the path specified: ''
  • BcK
    BcK about 6 years
    Ok I guess I understood your problem, you are trying to run the script from a different working directory, add the line on top of your code. >>> os.chdir(<path to your desktop>)
  • ZenB883
    ZenB883 about 6 years
    Thanks for helping me solve the problem and taking the time to answer my question @BcK