regular expression concatenation with strings

oscartheduck oscartheduck at gmail.com
Fri Jun 22 16:18:39 EDT 2007


Hi folks,

I have a little script that sits in a directory of images and, when
ran, creates thumbnails of the images. It works fine if I call the
function inside the program with something like "thumbnailer("jpg),
but I want to use a regular expression instead of a plain string so
that I can match jpeg, jpg, JPEG etc.



Here's the script:

---

 #!/usr/bin/env python
from PIL import Image
import glob, os, re

size = 128, 128

# takes an extension (e.g. jpg, png, gif, tiff) as argument
def thumbnailer(extension):
#glob the directory the script is in for files of the type
foo.extension
  for picture in glob.glob("*." + extension):
    file, ext = os.path.splitext(picture)
    im = Image.open (picture)
    im.thumbnail(size, Image.ANTIALIAS)
    im.save(file + ".thumbnail." + extension)


jpg = re.compile("jpg|jpeg", re.IGNORECASE)
thumbnailer(jpg)



---

And here's the error:

---

Traceback (most recent call last):
  File "./thumbnail.py", line 19, in ?
    thumbnailer(jpg)
  File "./thumbnail.py", line 11, in thumbnailer
    for picture in glob.glob("*." + extension):
TypeError: cannot concatenate 'str' and '_sre.SRE_Pattern' objects

---


It looks to me like the conversion to a regex object instead of a
plain string is screwing up the file glob + extension concatenation.
Is there a simple way to accomplish what I'm trying to do here and get
rid of that error?

Thanks!




More information about the Python-list mailing list