Search code examples
pythonrenamefile-rename

Python - how to change all file names into lowercases and without blanks


I'm trying to change all the files in a folder so that they contain some unity. For example, I have 'Hard Hat Person01', 'Hard Hat Person02' and so on but I also have 'hard_hat_person01' and 'hardhatperson01' in the same folder.

So I want to change all those file names into 'hardhatperson01', 'hardhatperson02' and so on. I tried the codes as below but it keeps showing errors. Can you please help me with this?

for file in os.listdir(r'C:\Document'):
    if(file.endswith('png')):
        os.rename(file, file.lowercase())
        os.rename(file, file.strip())

Solution

  • listdir only returns the filename, not its directory. And you can't rename the file more than once. In fact, you should make sure that you don't accidentally overwrite an existing file or directory. A more robust solution is

    import os
    
    basedir = r'C:\Document'
    
    for name in oslistdir(basedir):
        fullname = os.path.join(basedir, name)
        if os.path.isfile(fullname):
            newname = name.replace(' ', '').lower()
            if newname != name:
                newfullname = os.path.join(basedir, newname)
                if os.path.exists(newfullname):
                    print("Cannot rename " + fullname)
                else:
                    os.rename(fullname, newfullname)