I want to change the file names and folder names in a given directory and all subfolders. My folder structure is as follows:
- top directory
- file1
- file2
- folder1
- file1
- file2
- file3
- file4
- folder2
- file1
- file2
- file3
- file4
I get the following error when executing the code below. I already checked the forums, but couldn't find a solution. Could someone please help me solve this issue and let me know what I need to do to get the program working? Or is there a better solution for renaming files and folders in a tree?
Error message
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Filename 1' -> 'filename_1'
Code
#Change file names and folder names in a given directory and all its
subfolders
import os
os.chdir("path\\to\\folder")
print(os.getcwd())
#Walk the directory and change the file names and folder names in all folders and subfolders.
for root, dirs, files in os.walk("path\\to\\folder"):
for dir_name in dirs:
os.rename(dir_name, dir_name.replace(" ", "_").lower())
for file_name in files:
os.rename(file_name, file_name.replace(" ", "_").lower())
#Print done once all files have been renamed.
print("done")