Reputation: 87
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
Upvotes: 0
Views: 3275
Reputation: 23
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))
Upvotes: 2