Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.5: Moving files to folder based on filenames

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)
like image 378
ZenB883 Avatar asked Jun 13 '26 00:06

ZenB883


1 Answers

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)
like image 194
Primusa Avatar answered Jun 15 '26 14:06

Primusa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!