Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
image files renamer
# renames a directory of files with their image extension
# currently works with only JPEG and PNG files
# 2014.02.25 darell tan
import os
import sys
def id_file(filename):
"""Primitive (but cheap) method of identifying an image file."""
f = open(filename, 'rb')
sig =
if sig[:2] == '\xff\xd8':
return 'jpg'
elif sig[1:4] == 'PNG':
return 'png'
return None
def main():
d = sys.argv[1]
assert os.path.isdir(d)
for f in os.listdir(d):
if f == '.' or f == '..':
# form full path
fp = os.path.join(d, f)
# make sure it's a file
if not os.path.isfile(fp):
# does it already have an extension?
if f[-4:-3] == '.':
typ = id_file(fp)
if typ and not f.endswith(typ):
os.rename(fp, '%s.%s' % (fp, typ))
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.