I’m creating a small script to automatically convert files from .jpg to .png:
import glob, os
import Image
basedir = "C:\Users\User\Desktop\\fimg\images\\"
prefix = "picture"
def convert_png():
for jpg in glob.glob(os.path.join(basedir, '*.jpg')):
filename = f.rsplit('.')[-2]
njpg = Image.open(basedir + '%s.jpg' % (filename))
njpg.save(basedir + '%s.png' % (filename))
print "CONVERTED: " + filename + '.png'
for i, f in enumerate(os.listdir(basedir), 1):
convert_png()
But with this, it seems to convert the file multiple times (about 10) as it prints the converted message this amount, before moving onto the next file. Is there something wrong here that’s making it do this?
C:\Users\User\Desktop\fimg>python test.py
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 16094.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
CONVERTED: 185500.png
The problem was with the nested loops: The bottom
for, which then calledconvert_png, which itself had another loop. I eliminated the loop inconvert_pngand simplified the code somewhat by only calling that function when a file with a.jpgextension is found. Note the use ofsplitextto split the filename into its base and extension.