Skip to content

Instantly share code, notes, and snippets.

@sevaine
Created June 30, 2013 08:12
Show Gist options
  • Save sevaine/5894324 to your computer and use it in GitHub Desktop.
Save sevaine/5894324 to your computer and use it in GitHub Desktop.
Quick and dirty Python dictionary comprehension of os.listdir to build a dictionary of current dir and file names as keys, and provide their values as the "cleaned" file or dir names. Very handy when bulk renames of files containing spaces, or other non alphanum characters in their name are required.
#!/usr/bin/env python
""" load modules """
import os
import sys
""" What dir are we listing? """
target_dir = sys.argv[1]
""" Build dict """
rename_map = dict((k,v) for (k,v) in [ (x, ''.join([ y.strip('[]()') for y in x ]).replace(' ','_')) for x in os.listdir('.') ])
"""
For safetey reasons, print out the 'mv' commands that need to be run.
These could easily be swapped for a call to 'os.rename()'
"""
for (k,v) in rename_map.items():
sys.stdout.write("mv -v '%s' %s\n" % (k, v))
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment