Last active
December 20, 2019 16:58
-
-
Save X0RBYT3/7e93093c32fba6c1235a794332c2558b to your computer and use it in GitHub Desktop.
Mass File Renamer
This file contains 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
""" | |
mass file renamer. Obvious prototype but does the job. | |
Renames files according to extension (EXT0001), unless specified otherwise. | |
Neku 2019 | |
rename.py | |
optional parameters | |
-h --help: prints this help and exits | |
-s --specific: specifies a word you want in them, before the | |
-d --dir: uses directory specified, relative to current dir | |
-ad --abs: uses Absolute directory, regardless of current dir | |
-e --extension: only renames files with -e | |
""" | |
import os | |
import sys | |
from colored import fg, style | |
def print_red(string: str): | |
if not "colored" in sys.modules: | |
print("[-]" + string) | |
return None | |
print("%s" %fg(1) + string + style.RESET) | |
return None | |
def print_yellow(string: str): | |
if not "colored" in sys.modules: | |
print("[/]" + string) | |
return None | |
print("%s" %fg(3) + string+style.RESET) | |
return None | |
def print_green(string: str): | |
if not "colored" in sys.modules: | |
print("[+]" + string) | |
return None | |
print("%s" %fg(2) + string+style.RESET) | |
return None | |
# I like to specify these because honestly I'm too lazy to remember them. | |
usage = ('rename.py\n' | |
'\noptional parameters' | |
'\n-h --help: prints this help and exits' | |
'\n-s --specific: specifies a word you want in them, before the num' | |
'\n-d --dir: uses directory specified, relative to current dir' | |
'\n-ad --abs: uses Absolute directory, regardless of current dir' | |
'\n-e --extension: only renames files with -e') | |
class Renamer: | |
def __init__(self,**kwargs): | |
self.rel_dir = kwargs.get('dir',None) | |
self.abs_dir = kwargs.get('a_dir',None) | |
if self.abs_dir is '': | |
self.abs_dir = os.path.join(os.getcwd()+ self.rel_dir) | |
self.specific = kwargs.get('specific',None) | |
self.extension = kwargs.get('extension',None) | |
# Error handling | |
if not isinstance(self.rel_dir,str): | |
raise TypeError('Directory must be of type: String') | |
if not isinstance(self.extension, str): | |
raise TypeError('Extension must of type: String') | |
if self.extension is not '': | |
self.ext_str = 'Only renaming files with .{0} as an extension'.format(self.extension) | |
else: | |
self.ext_str = '' | |
def rename(self): | |
try: | |
os.chdir(self.abs_dir) | |
except FileNotFoundError: | |
print_red('Directory: {} could not be found.') | |
return False | |
print_yellow('Renaming files in {abs_dir}.\n{ext}' | |
'\nPress any key to continue. Press e to exit.\n'.format( | |
abs_dir=self.abs_dir, | |
ext=self.ext_str)) | |
continuation = input() | |
if continuation.lower() == 'e': | |
return False | |
final_counter = 0 | |
file_counter = {} # format: {'ext':count} | |
files = [f for f in os.listdir() if os.path.isfile(f)] | |
# For future, os.path.getctime() gets Creation time x | |
for file in files: | |
file_ext = file.split(".")[-1].upper() | |
if self.extension and file_ext.lower() != self.extension.lower(): | |
continue # next time ol friend | |
if self.specific: | |
count = file_counter.get('all',0) | |
if not count: | |
file_counter['all'] = 1 | |
else: | |
file_counter['all'] += 1 | |
file_name = self.specific+ str(count+1).zfill(4) + '.' + file_ext.lower() | |
else: | |
count = file_counter.get(file_ext,0) | |
if not count: # if it is 0 | |
file_counter[file_ext] = 1 | |
else: | |
file_counter[file_ext] += 1 | |
file_name = file_ext + str(count+1).zfill(4) + '.' + file_ext.lower() | |
print_green('Renaming {0} to {1}.'.format(file,file_name)) | |
os.rename(file,file_name) | |
final_counter += 1 | |
if final_counter: | |
print_green('\nFinished renaming files.\nNamed {0} in total.'.format(final_counter)) | |
else: | |
print_yellow('\nDid not rename any files? Check parameters and try again.') | |
return False | |
return True | |
def main(args): # may look like '-s Photos -d /Photos -e png | |
# could specify default params in kwargs.get, however, this allows me to change them from my args | |
kwargs = {'dir':'', | |
'a_dir':'', | |
'specific':None, | |
'extension':''} | |
for arg in args.replace('--','-').split("-"): # ['s Photos ',d /Photos ', 'png'] | |
arg = arg.strip() | |
if arg is '': | |
continue | |
if arg.lower().startswith('h') or arg.lower().startswith('help'): | |
print(usage) | |
return | |
elif arg.lower().startswith('s') or arg.lower().startswith('specific'): | |
kwargs['specific'] = "_".join(arg.split(" ")[1:]) | |
elif arg.lower().startswith('d') or arg.lower().startswith('dir'): | |
kwargs['dir'] = " ".join(arg.split(" ")[1:]) | |
elif arg.lower().startswith('ad') or arg.lower().startswith('abs'): | |
kwargs['a_dir'] = " ".join(arg.split(" ")[1:]) | |
elif arg.lower().startswith('e') or arg.lower().startswith('extension'): | |
kwargs['extension'] = " ".join(arg.split(" ")[1:]).replace('.','') | |
else: | |
print_red('ERROR: unsupported argument, will pass over it.\nArgument: {0}\n'.format(arg)) | |
R = Renamer(**kwargs) | |
if not R.rename(): | |
print_red('Exiting with Exit Code 0.') | |
if __name__ == '__main__': | |
print('\n\n') | |
main(' '.join(sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment