Search code examples
pythonuppercase

(python) recursively remove capitalisation from directory structure?


uppercase letters - what's the point of them? all they give you is rsi.

i'd like to remove as much capitalisation as possible from my directory structure. how would i write a script to do this in python?

it should recursively parse a specified directory, identify the file/folder names with capital letters and rename them in lowercase.


Solution

  • os.walk is great for doing recursive stuff with the filesystem.

    import os
    
    
    def lowercase_rename(folder):
        # renames all subforders of folder, not including folder itself
        def rename_all(root, items):
            for name in items:
                try:
                    os.rename(os.path.join(root, name), os.path.join(root, name.lower()))
                except OSError:
                    pass  # can't rename it, so what
    
        # starts from the bottom so paths further up remain valid after renaming
        for root, dirs, files in os.walk(folder, topdown=False):
            rename_all(root, dirs)
            rename_all(root, files)
    

    The point of walking the tree upwards is that when you have a directory structure like '/A/B' you will have path '/A' during the recursion too. Now, if you start from the top, you'd rename /A to /a first, thus invalidating the /A/B path. On the other hand, when you start from the bottom and rename /A/B to /A/b first, it doesn't affect any other paths.

    Actually you could use os.walk for top-down too, but that's (slightly) more complicated.