3

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 but I've yet to figure out how to move the files based on it's filename, 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 entire files in a folder to a destination that I want.

# Moving Files from one place to another
import shutil
import os 

sourcefile = 'Desktop/00/'
destination = 'Desktop/00/d'

# Loading the files from source
files = os.listdir(path=sourcefile)

# Reading the files in folder
for f in files:
    shutil.move(sourcefile+f, destination)
flamelite
  • 2,654
  • 3
  • 22
  • 42
ZenB883
  • 87
  • 1
  • 2
  • 10

1 Answers1

2

At this point all you need is to modify destination based on the last digit:

for f in files:
    folder_number = f.split('.')[0][-1]
    shutil.move(sourcefile+f, destination + '/' + folder_number + '/' + f)
Primusa
  • 13,136
  • 3
  • 33
  • 53
  • Thanks for answering my question, however when I tried to run the code this is what I got as an error. Error: Cannot move a directory 'Desktop/00/d' into itself 'Desktop/00/d/d'. – ZenB883 Apr 18 '18 at 02:04
  • this is an example script to give you an idea of what you can do. sourcefile+f shouldn't be a directory though could you tell me whats going on with that – Primusa Apr 18 '18 at 02:09
  • @ZenB883 I made some quick edits it should be working tell me if it isn't – Primusa Apr 18 '18 at 02:12
  • I see, I tried playing around with it and I do see that it does changes the filenames and it did move the last image in the list. These trial and errors is frustrating but at the sametime gives me an idea to what it's doing. Thank you for taking the time in helping me without giving me the answer and I appreciate that, I think I got it from here @Primusa – ZenB883 Apr 18 '18 at 02:15
  • hi @Primusa I was wondering if you could help answering another one of my questions, and it's an update to this one. Thanks again https://stackoverflow.com/questions/49893501/python-moving-files-to-folder-based-on-filenames – ZenB883 Apr 18 '18 at 07:57