Skip to content

Instantly share code, notes, and snippets.

@zhhailon
Created June 30, 2016 16:44
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 zhhailon/6559a29adc9d7b158ac6db954b5d4153 to your computer and use it in GitHub Desktop.
Save zhhailon/6559a29adc9d7b158ac6db954b5d4153 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
from os import chdir, getcwd, listdir
from os.path import realpath
from shutil import move
class PushdContext:
cwd = None
original_dir = None
def __init__(self, dirname):
self.cwd = realpath(dirname)
def __enter__(self):
self.original_dir = getcwd()
chdir(self.cwd)
return self
def __exit__(self, type, value, tb):
chdir(self.original_dir)
def pushd(dirname):
return PushdContext(dirname)
def bulk_rename():
parser = argparse.ArgumentParser(description='Bulk rename files.')
parser.add_argument('directory', metavar='DIR', help='a directory')
parser.add_argument('indices', metavar='N', type=int,
nargs='+',choices=range(1, 13), help='an index')
args = parser.parse_args()
with pushd(args.directory) as ctx:
for f in listdir(ctx.cwd):
print('Renaming "%s"' % f)
ext = f.split('.', 1)[1]
name = f.split('.', 1)[0]
parts = name.split('_')
new_name = ''
for i in args.indices:
new_name += parts[i-1] + '_'
new_name = '%s.%s' % (new_name[:-1], ext)
print('\tto "%s"...' % new_name)
move(f, new_name)
if __name__ == "__main__":
bulk_rename()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment