Created
February 25, 2014 15:48
-
-
Save geekman/9211524 to your computer and use it in GitHub Desktop.
image files renamer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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