Python — Script to Rename Files and Crop Images in Directory

I’m often using python to rename files for me or process them in batches when I need to save some time / immense boredom, and I do it so infrequently I generally have to look at reference material.

Here some code for future reference.

Python Rename Script

This is just some one off code I wrote to save myself from doing repetative tasks. 

It probably took as long as manually renaming them and cropping the files.

The source files were in this format:
- name fun.jpg
- name work.jpg

I needed them in the following format:
- team_name.jpg
- team_name2.jpg 

and at specific dimensions.

I at first just wanted to rename, but found out some images were odd sizes.

import re
import os
import shutil
from PIL import Image, ImageOps

dirname = os.path.abspath('.')
file_paths = os.listdir(dirname)

for _file in file_paths:
        matches = re.findall('(.*) (fun|work)\.jpg', _file)[0] # find name & if fun or work.
        name = matches[0]
        _type = matches[1]
        prefix = 'team_'
        suffix = ''
        if _type == 'fun':
            suffix = '2'
        new_name = prefix + name  + suffix + '.jpg'
        image =
        imagefit =, (150, 170), Image.ANTIALIAS, 0, (0.5, 0))'tmp/'+ new_name, 'JPEG', quality=90)
    except Exception, e:
        print e, _file
        # I don't really care about when this fails..
        # it would fail on any regex match failure like .DS_STORE (OSX file)
        # or my tmp directory

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s