Jack Bird Jack Bird - 3 months ago 14
Python Question

Python loop through folders and rename files

I am trying to go through a bunch of folders and go into each one and rename specific files to different names. I got stuck on just the loop through folders part.

My file system looks as follows:

Root Directory
Folder
File1
File2
File3
Folder
File1
File2
File3


The code I have is:

os.chdir(rootDir)

for folder in os.listdir():
print(folder)
os.chdir(rootDir + 'folder')
for f in os.listdir():
print(f)
os.chdir(rootDir)


So in my mind it will go through the folders then enter the folder and list the files inside then go back to the root directory

Answer

Have a look at os.walk

import os
for dir, subdirs, files in os.walk("."):
    for f in files:
        f_new = f + 'bak'
        os.rename(os.path.join(root, f), os.path.join(root, f_new))
Comments