Python importing a batch of jpg images in files? - python-3.x

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 = # Opening image
fileName, fileExt = os.path.splitext(img) # Extract the filename and
# Extension from path'*.jpg') #save the image to new folder from
#old folder

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:
=> ('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 =
filepath, filenameExt = os.path.split(img)
filename, fileExt = os.path.splitext(filenameExt)
folderNumber = filename.split("_")[1]"{}/{}/{}".format(newfold, folderNumber, filenameExt))


How to store non repeating images in a different directory using Python 3 ?

I have the following code which lists all images in a directory. In the output of this code, I have an image and matching XML to each image. My question is: How do I add the image files without matching xml notation (image 0,image1 and image2)to a new folder?
import os
# detect the current working directory
path = os.getcwd()
# read the entries
with os.scandir(path) as listOfEntries:
for entry in listOfEntries:
# print all entries that are files
if entry.is_file():

Python script to move specific files from one folder to another

I am trying to write a script (python 2.7) that will use a regex to identify specific files in a folder and move them to another folder. When I run the script, however, the source folder is moved to the target folder instead of just the files within it.
import os, shutil, re
src = "C:\\Users\\****\\Desktop\\test1\\"
#src = os.path.join('C:', os.sep, 'Users','****','Desktop','test1\\')
dst = "C:\\Users\\****\\Desktop\\test2\\"
#dst = os.path.join('C:', os.sep, 'Users','****','Desktop','test2')
files = os.listdir(src)
#regexCtask = "CTASK"
print files
#regex =re.compile(r'(?<=CTASK:)')
#print src, dst
regex = re.compile('CTASK*')
for f in files:
if regex.match(f):
filescr= os.path.join(src, files)
So basically there are files in "test1" folder that I want to move to "test2", but not all the files, just the ones that contain "CTASK" at the beginning.
The **** in the path is to protect my work username.
Sorry if it is messy, I am still trying a few things out.
You need to assign path to exact file (f) to filescr variable on each loop iteration, but not path to files (files - is a list!)
Try below code
import os
from os import path
import shutil
src = "C:\\Users\\****\\Desktop\\test1\\"
dst = "C:\\Users\\****\\Desktop\\test2\\"
files = [i for i in os.listdir(src) if i.startswith("CTASK") and path.isfile(path.join(src, i))]
for f in files:
shutil.copy(path.join(src, f), dst)

How to rename JPG files with running order using Python

I quite new in Python programming and i try to rename 100 files with ".jpg" extention, located in specific folder using pyhthon.
I need that the files will be renamed by running order start from number 1. This is the code i start writing:
import os,glob,fnmatch
for files in glob.glob("*.jpg"):
print files
When i run it, i get:
so the code, till now is OK.
For example my folder is:
and i need that all the files name will be:
1,2,3,4 - with running order names. Is it possible with python 2.7?
If you simply want to rename all files as 1.jpg, 2.jpg etc. you can do this:
import os
import glob
for index, oldfile in enumerate(glob.glob("*.jpg"), start=1):
newfile = '{}.jpg'.format(index)
os.rename (oldfile,newfile)
enumerate() is used to get get the index of each file from the list returned by glob(), so that it can be used to create the new filename. Note that it allows you to specify the start index, so I've started from 1, rather than Python Standard, zero
If you want this list of files to be sortable properly, you'll want the filename to be padded with zero's as well (001.jpg, etc.). In which case simply replace newfile = '{}.jpg'.format(index+1)' with newfile = '{:03}.jpg'.format(index).
See the the docs for more on str.format()
To rename all the JPG files from a particular folder First, get the list of all the files contain in the folder.
os.listdir will give you list all the files in images path.
use enumerate to get the index numbers to get the new name for
import os
images_path = r"D:\shots_images"
image_list = os.listdir(images_path)
for i, image in enumerate(image_list):
ext = os.path.splitext(image)[1]
if ext == '.jpg':
src = images_path + '/' + image
dst = images_path + '/' + str(i) + '.jpg'
os.rename(src, dst)

Take a file directory consisting of files and write all files to a folder with different names in another folder

I want to take a list of files from directory and convert all those images into thumbnail images. The following code can write a single file as thumnail.png. How can i write all images like ""Thumbnail1.png","PNG") to thumnbnailN.png" . I want all files to be converted and written to a folder. How can i do that? Thanks in Advance.
from PIL import Image
from numpy import *
import os
def get_imlist(path):
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.png')]
for file in filelist:
im = im.resize(size, Image.ANTIALIAS)"Thumbnail.png","PNG")
imgArr = array(im)
#print imgArr.shape
I'd replace your imlist stuff with glob. That way you can use something like
for file in glob.iglob('D:/path/*.png')
And you should look more into os.path. Specifically os.path.split and os.path.splitext.

How do I batch extract metadata from DM3 files using ImageJ?

How can you extract metadata for a batch of images? My first thought was to record a macro and then modify it to operate on a list of file names.
In that vein, I tried recording a macro doing something like this:
Ctrl-o # Open a file
12.dm3Enter # Select file to open
Ctrl-i # Open metadata in a new window
Ctrl-s # Save file
Info for 12.txtEnter# Name of file being saved
Ctrl-w# Close current window
Ctrl-w# Close current window
These steps work when I do them manually. This results in the following macro, which seems to be missing most of what I tried to record:
run("Show Info...");
Modifying a Jython script that is supposed to extract dimension metadata from an image:
from import File
from loci.formats import ImageReader
from loci.formats import MetadataTools
import glob
# Create output file
outFile = open('./pixel_sizes.txt','w')
# Get list of DM3 files
filenames = glob.glob('*.dm3')
for filename in filenames:
# Open file
file = File('.', filename)
# parse file header
imageReader = ImageReader()
meta = MetadataTools.createOMEXMLMetadata()
# get pixel size
pSizeX = meta.getPixelsPhysicalSizeX(0)
# close the image reader
outFile.write(filename + "\t" + str(pSizeX) + "\n")
# Close the output file
You could use getImageInfo() instead of run("Show Info..."). This will create a string in the macro containing the run("Show Info...") output, but can then be modified as you like. See for more information.