Skip to content
Advertisement

File not found error in os.rename

I am trying to write a program to categorize into folders a large amount of files according to their respective groups indicated in the file name. I wrote the followin code, but when I run it it gives me a file not found error, even though the file is in the given path. I’d appreciate any help in figuring out what is wrong.

JavaScript

Here’s the error:

JavaScript

Advertisement

Answer

os.rename does not automatically create new directories (recursively), if the new name happens to be a filename in a directory that does not exist.

To create the directories first, you can (in Python 3) use:

JavaScript

where dirname can contain subdirectories (existing or not).


Alternatively, use os.renames, that can handle new and intermediate directories. From the documentation:

Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement