Reputation: 111
i'm trying to write a script that goes through the current working directory and all of it's sub directories and changes the file names, here is my code:
from os import rename, listdir, getcwd, walk
from os.path import isdir, join
for root, dirs, files in walk(getcwd()):
for name in files:
rename(join(root, name), join(root, name.replace("Season ", "S")))
rename(join(root, name), join(root, name.replace("season ", "S")))
rename(join(root, name), join(root, name.replace("Episode ", "E")))
rename(join(root, name), join(root, name.replace("episode ", "E")))
I'm getting an error saying "No such file or directory", though the error contains a file name given from walk(), so it is an actual file.
looking through the files, I see it works once every time before crashing.
any help? I've had a different script that does the same thing, only in a single directory, but I needed it to work in sub-directories too.
Upvotes: 0
Views: 669
Reputation: 59095
Looks like you're trying to rename each file multiple times. After you rename it once, it won't have the name it had before, so you get a "no such file". You should probably do all the modifications to the intended name before doing a single rename per file.
newname = name.replace("Season ", "S")
newname = newname.replace("season ", "S")
newname = newname.replace("Episode ", "E")
newname = newname.replace("episode ", "E")
rename(join(root, name), join(root, newname))
Upvotes: 2