Search code examples
pythonuppercase

Python: How to change a filename to lowercase but NOT the extension


I'm trying to change filenames like WINDOW.txt to lowercase but then I also need to change the extension .txt to uppercase. I am thinking I can just change the entire thing to lowercase as the extension is already lowercase and then using something like .endswith() to change the extension to uppercase but I can't seem to figure it out. I know this may seem simple to most so thank you for your patience.


Solution

  • This one handles filenames, paths across different operating systems:

    import os.path
    
    def lower_base_upper_ext(path):
        """Filename to lowercase, extension to uppercase."""
        path, ext = os.path.splitext(path)
        head, tail = os.path.split(path)
        return head + tail.lower() + ext.upper()
    

    It leaves possible directory names untouched, just the filename portion is lower-cased and extension upper-cased.