Convert all files and directories in a folder from snake_case to lowerCamelCase using Python

Yoseph
2 min readAug 30, 2021

Recently, I had written a project in Typescript and for whatever reason decided to use snake_case as the format for all naming. When the time came to merge the code into the main repository, the repository organizers said I needed to change everything from snake_case to lowerCamelCase. Ok. No problem.

I’m lazy so first thing I did was google how to do this. I started off seeing if there was a bash script for it. I found this StackOverflow answer: shell script — Convert underscore to PascalCase, ie UpperCamelCase — Unix & Linux Stack Exchange.

It did some of what I wanted, but not everything, and I was a bit annoyed with the bash scripting limitations for regex, particularly with sed . That being said, I wrote a little bash script and it did some of what I wanted:

#!/bin/bash
find . -name "*.ts" | while IFS= read -r fname; do
ccase=`echo $fname | sed -E 's/_(.)/\U\1/g'`
echo $ccase
mv "$fname" "$ccase"
# dirname=`dirname "$fname"`
# filename=`basename "$fname"`
# arr=(${filename//_/ })
# printf -v ccase %s "${arr[@]^}"
# mv "${dirname}/$filename" "${dirname}/$ccase"
# newname=`echo "$filename" | sed -r "s/(^|_/([a-z])/\U\2/g"`
done

But it doesn’t do anything for the directory names, and nesting? So I gave up on bash and went to Python, where the builtin libraries working with directories and regex feel easier to use for me. I started with an article that gave me the regex I needed for rewriting underscore / snake_case to lowerCamelCase: Snake case to camel case and back using regular expressions and Python — DEV Community.

That gave me the code for a small function that would, given a string, convert things from snake_case / underscode to lowerCamelCase:

def snake_to_camel(inputstring):
REG = r"(.*?)_([a-zA-Z])"
def patternrepl(match):
return match.group(1).lower() + match.group(2).upper()
results = re.sub(REG, patternrepl, inputstring, 0)
return result

Combining this with a recursive function to traverse down through the directory structure and process only typescript files, I ended up with the following code block:

I hope you find this code helpful!

--

--

Yoseph

Software Engineer passionate about the future of cities. Currently building libraries for Azure IoT.