Feral Cat

Building just because.
python

Programmatically Renaming File Paths with Python

Programmatically renaming file paths with Python has made my life easier in more ways than we have time for in this article. Am I being dramatic? Most definitely.

That being said, it is a ridiculously time saving hack to learn. For example did your company’s name recently change and now you’re faced with updating a million folder names? Did you start a programming project with a random ass name like “random-ass-name” and then have it turn into a serious endeavor all of a sudden? Then you can definitely benefit from learning how to do it in Python.

So, we’ll be feeding the script a starting path. The script will then look for all folders and rename them.

dst = '/Users/yourUserName/path/to/folder' # <- starting path
for dirpath, dirnames, filenames in os.walk(dst):
    for dirpath, dirnames, filenames in os.walk(dst):
        dirpath1 = dirpath.replace(lowerCaseTranslation, lowerCaseNewTranslation)
        if dirpath != dirpath1:
            os.rename(dirpath, dirpath1)
            # print(dirpath1) 

dst is the folder you want your script to start at. From there it will start working through the tree and rename files and folders. Line 2 starts looping through what os.walk() finds.

Conclusion

All in all, I’m hoping this will save you some time. There’s nothing worse than having to do busy work. If you’re looking for something juicer to dig into check out my brief overview of modulos here. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *