balter
balter

Reputation: 25

Renaming files and folders with the os.walk in Python 3

I am trying to rename all files and folders in a given directory. Id like to replace a space with a hyphen and then rename all to lowercase. I am stuck with the code below. When os.rename is commented out, the print function returns all files as expected, however when I uncomment os.rename I get an error stating that file XYZ -> x-y-z cant be found.

import os

folder = r"C:\Users\Tim\Documents\storage"
space = " "
hyphen = "-"

for root, dirs, files in os.walk(folder):
    for file in files:
        if space in file:
            newFilename = filename.replace(space, hyphen).lower()
            os.rename(file, newFilename)
            print(newFilename)

Obvioulsy this is just for the files but I'd like to apply the same logic to folders too. Any help would be greately appreciated. Pretty new at Python so this is a little beyond me! Thanks so much.

Upvotes: 2

Views: 2008

Answers (1)

Lie Ryan
Lie Ryan

Reputation: 64837

os.rename() resolves relative file paths (paths that doesn't start with a / in Linux/Mac or a drive letter in Windows) relative to the current working directory.

You'll want to os.path.join() the names with root before passing it to os.rename(), as otherwise rename would look for the file with that name in the current working directory instead of in the original folder.

So it should be:

os.rename(os.path.join(root, file), os.path.join(root, newFilename))

Upvotes: 1

Related Questions