Search code examples
pythontraversaldirectorysubdirectoryos.walk

How to retrieve the name of the current folder with os.walk?


I have a main folder within which there are a number of sub folders:

MAIN FOLDER
---+ SUB FOLDER 1
     ---+ FILE 1  
---+ SUB FOLDER 2
     ---+ FILE 2
---+ SUB FOLDER 3
     ---+ FILE 3

I am traversing this tree with the purpose of doing some calculations, but I need to keep track of the path of each sub folder. I am using os.walk().

I have come up with this partial solution, which prints out the names of all the folders. I want to ignore the Main Folder and focus on the sub folders only, but I got stuck as I don't know how to properly define/call/specify the complete path of the current sub folder:

import os
directoryPath=r'C:\Users\MyName\Desktop\Main_Folder'
for folders, sub_folders, file in os.walk(directoryPath):
       print('Found directory: %s' % folders)

How can I retrieve the complete path of the current sub folder?


Solution

  • To answer the OP's question, sorry to to do this 5 years late btw, I imagine your deadline is way over, but it would be something like this:

    for root, dirs, files in os.walk(pathName):
       for f in files:
          print("current folder".format(root))