Skip to content

Instantly share code, notes, and snippets.

@Ovyerus
Last active May 3, 2017 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ovyerus/c918aa459bd7728c1c56482b85e5cc86 to your computer and use it in GitHub Desktop.
Save Ovyerus/c918aa459bd7728c1c56482b85e5cc86 to your computer and use it in GitHub Desktop.
Script to rename all files in current directory
import os, re, argparse, sys
from datetime import datetime
parser = argparse.ArgumentParser(description='Rename files to have a prefix of their created date.')
parser.add_argument('-v', '--version', action='version', version='%(prog)s v2.0', help='Display the version of the program.')
parser.add_argument('-f', '--file', default=' ', type=str, help='Choose which file to rename.')
parser.add_argument('-d', '--directory', default='./', type=str, help='Choose a directory to rename all files in.')
parser.add_argument('-i', '--ignore', default='@', type=str, help='Choose ignore files starting with a character.')
args = parser.parse_args()
rename_dir = args.directory
ignore_char = args.ignore
if not rename_dir.endswith('/'):
rename_dir += '/'
def yes(confirm):
return (confirm == '') or (re.match('^y(es)?$', confirm) is not None)
def no(confirm):
return re.match('^no?$', confirm) is not None
def confirm_loop(msg):
sys.stdout.write(msg)
confirm = input().lower()
if yes(confirm):
return True
elif no(confirm):
return False
else:
print('Invalid response\n')
return confirm_loop()
def rename_files():
amt = 0
files = [f for f in next(os.walk(rename_dir))[2] if not f.startswith(ignore_char)]
if len(files) == 0:
return 0
else:
for file in files:
rename_file(rename_dir + file)
amt += 1
return amt
def rename_file(file):
file_time = datetime.fromtimestamp(os.stat(file).st_mtime)
file_name = '{}{}-{}-{} {}'.format(rename_dir, str(file_time.year), str(file_time.month).zfill(2), str(file_time.day).zfill(2), file[len(rename_dir):])
os.rename(file, file_name)
print('Renamed "{}"'.format(file_name[len(rename_dir):]))
if args.file == ' ':
print('This will rename all files in "{}" except those starting with "{}".'.format(rename_dir, ignore_char))
if confirm_loop('Do you wish to continue [Y/n]? '):
rename_amt = rename_files()
print('Renamed {} files.'.format(rename_amt))
else:
print('Exiting...')
sys.exit()
else:
print('This will rename the file "{}"'.format(args.file))
if (confirm_loop('Do you wish to continue [Y/n]? ')):
rename_file(args.file)
else:
print('Exiting...')
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment