0

I'm trying to import a batch of images from a file to a new separate folder according to the images name for example; 1000_70.jpg --> folder 70 and 1200_71.jpg --> folder 71. However, when I ran the script it does nothing.

from PIL import Image
import glob
import os



folder='Desktop/n' # All jpegs are in this folder
imList=glob.glob(folder+'*.jpg') # Reading all images with .jpg
newfold = 'Desktop/n/l' # New folder path


for img in imList: # Loop
    im = Image.open(img) # Opening image
    fileName, fileExt = os.path.splitext(img) # Extract the filename and 
                                               #  Extension from path
    im.save(newfold+fileName+'*.jpg')  #save the image to new folder from 
                                        #old folder
ZenB883
  • 87
  • 1
  • 2
  • 10

1 Answers1

2

First of you want the filename of the image not the path, use split instead of splitext to remove the parent folder and than use splitext to remove the extension:

os.path.splitext("afdsasdf/fasdfa/fff.jpg")
=> ('afdsasdf/fasdfa/fff', '.jpg')
os.path.split("afdsasdf/fasdfa/fff.jpg")
=> ('afdsasdf/fasdfa', 'fff.jpg')

Second you remove the wildcare in *.jpg when saving the image. You need that wildcare with glob since you are selectioning multiple files.

Third you need to extract the second number in the filename (1000_70.jpg --> 70).

All toghether you should have something that look like this:

for img in imList:
    im = Image.open(img)
    filepath, filenameExt = os.path.split(img)
    filename, fileExt = os.path.splitext(filenameExt)
    folderNumber = filename.split("_")[1]
    im.save("{}/{}/{}".format(newfold, folderNumber, filenameExt))
pBabin
  • 23
  • 1
  • 4
  • I tried but still it's not creating the folder and importing the images. Also thank you for taking the time in answering my question. – ZenB883 Apr 18 '18 at 01:13
  • new question - updated @pBabin - Thanks, https://stackoverflow.com/questions/49893501/python-moving-files-to-folder-based-on-filenames – ZenB883 Apr 18 '18 at 07:58