Skip to content

Instantly share code, notes, and snippets.

@katychuang
Created April 24, 2013 18:48
Show Gist options
  • Select an option

  • Save katychuang/5454525 to your computer and use it in GitHub Desktop.

Select an option

Save katychuang/5454525 to your computer and use it in GitHub Desktop.
Rename images in a directory
"""
Title: Batch Image File Renaming
Author: Kat Chuang @katychuang
Copied from http://stackoverflow.com/questions/9835243/python-rename-multiple-image-files
"""
import os
# Create a list of files from the current directory who's last 4 characters
# as lowercase are either '.jpg'
files = [f for f in os.listdir('.') if f[-4:].lower() == '.jpg']
DRYRUN = True
for (index, filename) in enumerate(files):
extension = os.path.splitext(filename)[1]
# Define new file name pattern
newname = "PyCon2013-%0d%s" % (index, extension)
if os.path.exists(newname):
print "Cannot rename %s to %s, already exists" % (filename, newname)
continue
if DRYRUN:
print "Would rename %s to %s" % (filename, newname)
else:
print "Renaming %s to %s" % (filename, newname)
os.rename(filename, newname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment