File not found error in os.rename

后端 未结 1 1030
北海茫月
北海茫月 2021-01-27 21:19

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

相关标签:
1条回答
  • 2021-01-27 21:41

    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:

    os.makedirs(dirname, exist_ok=True)
    

    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

    0 讨论(0)
提交回复
热议问题