Search code examples
pythonoperating-systemuppercase

Uppercase the names of multiple files in a directory in Python


I'm working on a small project that requires that I use Python to uppercase all the names of files in a certain directory "ex: input: Brandy.jpg , output: BRANDY.jpg". The thing is I've never done on multiple files before, what I've done was the following:

universe = os.listdir('parallel_universe/')
universe = [os.path.splitext(x)[0].upper() for x in universe]

But what I've done capitalized the names in the list only but not the files in the directory itself, the output was like the following:

['ADAM SANDLER','ANGELINA JULIE','ARIANA GRANDE','BEN AFFLECK','BEN STILLER','BILL GATES', 'BRAD PITT','BRITNEY SPEARS','BRUCE LEE','CAMERON DIAZ','DWAYNE JOHNSON','ELON MUSK','ELTON JOHN','JACK BLACK','JACKIE CHAN','JAMIE FOXX','JASON SEGEL', 'JASON STATHAM'] 

What am I missing here? And since I don't have much experience in Python, I'd love if your answers include explanations for each step, and thanks in advance.


Solution

  • Right now, you are converting the strings to uppercase, but that's it. There is no actual renaming being done. In order to rename, you need to use os.rename

    If you were to wrap your code with os.rename, it should solve your problem, like so:

    [os.rename("parallel_universe/" + x, "parallel_universe/" + os.path.splitext(x)[0].upper() + os.path.splitext(x)[1]) for x in universe]
    

    I have removed the assignment universe= because this line no longer returns a list and you will instead get a bunch on None objects.

    Docs for os.rename: https://docs.python.org/3/library/os.html#os.rename