Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
image files renamer
#!/usr/bin/python
#
# 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 = f.read(4)
f.close()
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 == '..':
continue
# form full path
fp = os.path.join(d, f)
# make sure it's a file
if not os.path.isfile(fp):
continue
# does it already have an extension?
if f[-4:-3] == '.':
continue
print(f)
typ = id_file(fp)
if typ and not f.endswith(typ):
os.rename(fp, '%s.%s' % (fp, typ))
if __name__ == '__main__':
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.