Skip to content

Instantly share code, notes, and snippets.

@kranthilakum
Last active February 17, 2023 03:51
Show Gist options
  • 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
@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