Skip to content

Instantly share code, notes, and snippets.

@kbd
Created September 11, 2016 19:49
Show Gist options
  • Save kbd/ad1e2a1b752b7a0f297ee69990c77adc to your computer and use it in GitHub Desktop.
Save kbd/ad1e2a1b752b7a0f297ee69990c77adc to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import re
import sys
def get_new_path(path):
# find the number in the filename, looks like "#5"
filename = os.path.basename(path)
match = re.search(r'#(\d+)', filename)
if not match:
return None
number = match.group(1)
# make this operation idempotent
# i.e. if the output already starts with the number prefix, don't prepend
number_prefix = '{} - '.format(number)
if filename.startswith(number_prefix):
return None
output_filename = '{}{}'.format(number_prefix, filename)
output_path = os.path.join(os.path.dirname(path), output_filename)
return output_path
def rename_file(path):
new_path = get_new_path(path)
if not new_path:
print("Not renaming '{}'".format(path))
return # don't rename
else:
print("Renaming '{}' to '{}'".format(path, new_path))
os.rename(path, new_path)
if __name__ == '__main__':
"""take a list of files as input and rename the files"""
files = sys.argv[1:]
for file in files:
rename_file(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment