Skip to content

Instantly share code, notes, and snippets.

@kranthilakum
Last active February 17, 2023 03:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kranthilakum/7536042 to your computer and use it in GitHub Desktop.
Save kranthilakum/7536042 to your computer and use it in GitHub Desktop.
Python script to replace underscores with spaces
#!/usr/bin/python
# Usage: python rename_files.py "C:\Directory of Files with Underscores"
import os
import sys
directory = sys.argv[1] # parse through file list in the current directory
for filename in os.listdir(directory): # parse through file list in the current directory
if filename.find("_") > 0: # if an underscore is found
newfilename = filename.replace("_"," ") # convert underscores to space's
newfilename.lower() # convert to lower case
os.rename(filename, newfilename) # rename the file
@timbaileyjones
Copy link

Thank you for giving me a good starting point. I made a similar gist that renames files AND directories containing spaces, and also uses the 'svn mv' command to do the renames. This has the effect of doing the renames in SVN workspaces where other people have already committed files containing spaces. Hoping somebody finds it useful.

https://gist.github.com/linuxtampa/8156229

@benwiggy
Copy link

Thanks for this. Your second last line doesn't convert to lowercase: you need:

newfilename = newfilename.lower()

Otherwise you're just sending the lower case value to stdout.
I use the following to give first char as caps:

newNewfilename = newfilename[0].upper() + newfilename[1:].lower()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment