Skip to content

Instantly share code, notes, and snippets.

@Perlence
Created January 1, 2016 12:51
Show Gist options
  • Save Perlence/9ab37ceffaa9d1a35c05 to your computer and use it in GitHub Desktop.
Save Perlence/9ab37ceffaa9d1a35c05 to your computer and use it in GitHub Desktop.
Rename multiple files
#!/usr/bin/env python2
import glob
from itertools import takewhile
import os
import subprocess
import sys
import tempfile
EDITOR = 'c:\\Program Files\\Sublime Text 3\\sublime_text.exe'
args = sys.argv[1:]
if not args:
sys.exit('No files supplied')
# Run glob for each argument until '--'
itargs = iter(args)
globs = takewhile(lambda x: x != '--', itargs)
files = reduce(lambda a, b: a + glob.glob(b), globs, []) + list(itargs)
# Create temp file and write filenames into it
with tempfile.NamedTemporaryFile(mode='w', delete=False) as fp:
fp.write('\n'.join(files))
# Run EDITOR for temp file
subprocess.Popen([EDITOR, fp.name])
# Wait for user prompt
try:
raw_input('Press ENTER when ready ')
except KeyboardInterrupt:
sys.exit('')
# Read contents of the file
with open(fp.name) as fp:
newfiles = fp.read().splitlines()
os.unlink(fp.name)
# Rename files
for old, new in zip(files, newfiles):
os.rename(old, new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment