[EMAIL PROTECTED] wrote: > Hope it's not inappropriate to post this here. > > Could someone critique my code? I have no Python programmers in my > office to show this to. The script works OK, but should I do it > differently? I especially don't like how I check to see if jpegs exist. > > The style may not be acceptable to some, but I'm concerned with > substance, not style. Is there a 'more appropriate' way to do this? > > Thanks to all who take the time to give advice! > > ----------------------------------------------------------------- > import os > import os.path > #From PIL > import Image > > def tiff_to_jpeg(path): > > for root, dirs, files in os.walk(path): > for f in files: > if os.path.splitext(os.path.join(root,f))[1].lower() == > ".tif": > > # If a jpeg is already present. Don't do anything. > if > os.path.isfile(os.path.splitext(os.path.join(root,f))[0] + ".jpg"): > print "A jpeg file already exists for %s" %f > > # If a jpeg is *NOT* present, create one from the tiff. > else: > outfile = os.path.splitext(os.path.join(root,f))[0] > + ".jpg" > try: > im = Image.open(os.path.join(root,f)) > print "Generating jpeg for %s" %f > im.thumbnail(im.size) > im.save(outfile, "JPEG", quality=100) > except Exception, e: > print e > > # Run Program > path = '.' > tiff_to_jpeg(path) > The methodology seems just fine. You may (or may not) find the following code easier to read (not tested):
for f in [file for file in files if file.lower().endswith('.tif')]: # If a jpeg is already present. Don't do anything. filename, extension=f.split('.') jpgfile="%s.jpg" % filename jpgpath=os.path.join(root, jpgfile) # If a jpeg is *NOT* present, create one from the tiff. if not os.path.isfile(jpgpath): try: im = Image.open(os.path.join(root,f)) print "Generating jpeg for %s" % f im.thumbnail(im.size) im.save(jpgpath, "JPEG", quality=100) except Exception, e: print e continue print "A jpeg file already exists for %s" % f This code: 1) only processess .tif files 2) simplifies things by eliminating the splitext methods and slicing operations. 3) eliminates else branch -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list