Skip to main content

Recently I needed to go through all the folders in a directory and create an operation for all the files inside them, I was able to generate the absolute path for the files using os.join but the application which I had to run inside each of those folders wanted me to make the each folder as the current directory. os.walk is a recursive call and will go through all the folders and hence the best way to make sure that the current directory of os.walk is the current directory for OS is shown in the below code.

from os import listdir
from os.path import isfile, join
import os
import re

top = os.getcwd()

for (dirname, dirs, files) in os.walk(os.getcwd()):        
        for filename in files:
                os.chdir(dirname)
                # Add all the operations for your current working folder here 
                os.chdir(top)

'''
Additional ways to get the paths from os.walk
os.path.abspath(os.path.join(dirname, filename))
os.path.abspath(dirname)
os.chdir(dirname)
'''

Leave a Reply