Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created September 19, 2011 16:41
Show Gist options
  • Save igniteflow/1226919 to your computer and use it in GitHub Desktop.
Save igniteflow/1226919 to your computer and use it in GitHub Desktop.
Python script to rename files in directory, transforming spaces to hyphens and the chars to lowercase
import os
"""
Renames the filenames within the same directory to be Unix friendly
(1) Changes spaces to hyphens
(2) Makes lowercase (not a Unix requirement, just looks better ;)
Usage:
python rename.py
"""
path = os.getcwd()
filenames = os.listdir(path)
for filename in filenames:
os.rename(filename, filename.replace(" ", "-").lower())
@josean7link
Copy link

Thank you, that's what i was looking for.

@dicharal
Copy link

Does it read the names in ascending order?

@typopaul
Copy link

typopaul commented Oct 1, 2019

Great! It’s simple, it works. 👍 Thank you!

@rdegges
Copy link

rdegges commented Oct 25, 2019

There's a simpler way to do this using the linux rename command, if you'd like:

rename --force 's/ /-/g' *

If you run that on the CLI it'll rename all files in the current directory -- exchanging spaces for dashes.

@Lewiscowles1986
Copy link

@rdegges that does not make uppercase -> lowercase though.

@darshan4255
Copy link

how can i change only the first letter of a filename into uppercase??

@askfriends
Copy link

how about removing leading space in multiple files in a directory?
i have many files in a directory and each one start with a space. so how to batch remove that?

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