Last active
March 4, 2020 13:06
-
-
Save af-inet/14ee2b388f16f2a5ee8e4a4d1141a4d3 to your computer and use it in GitHub Desktop.
rename files to their inferred extension
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
| import os | |
| import os.path | |
| import glob | |
| import argparse | |
| try: | |
| import filetype | |
| except ImportError as e: | |
| print('missing package "filetype", try running:') | |
| print("pip install filetype") | |
| exit(1) | |
| def parse_args(): | |
| parser = argparse.ArgumentParser( | |
| description="rename files to their correct file extension" | |
| ) | |
| parser.add_argument( | |
| "path", | |
| nargs="+", | |
| help="pathname to a file you want to rename", | |
| ) | |
| parser.add_argument( | |
| "-f", | |
| "--force", | |
| action="store_true", | |
| help="actually rename files instead of dry-running", | |
| ) | |
| return parser.parse_args() | |
| def name_ext(filename): | |
| parts = filename.split(".") | |
| name = ".".join(parts[0:-1]) | |
| ext = parts[-1] | |
| return (name, ext) | |
| def mv(args, original_filename, new_filename): | |
| if args.force: | |
| os.rename(original_filename, new_filename) | |
| print(f"renamed: {original_filename} {new_filename}") | |
| else: | |
| print( | |
| f"would have renamed: {original_filename} {new_filename} (run with -f to rename)" | |
| ) | |
| def maybe_rename_file(args, filename): | |
| kind = filetype.guess(filename) | |
| if kind is None: | |
| print(f"[!] cannot guess: {filename}") | |
| else: | |
| name, ext = name_ext(filename) | |
| if ext != kind.extension: | |
| new_filename = ".".join([name, kind.extension]) | |
| mv(args, filename, new_filename) | |
| def main(args): | |
| for filename in args.path: | |
| if os.path.isfile(filename): | |
| maybe_rename_file(args, filename) | |
| if __name__ == "__main__": | |
| main(parse_args()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment