Reputation: 127
I have a directory which has the following form :
A/ : the root
B/: The first level subdirectory which contains the following directories
01/ 02/ 03/ 04/ 05/ 06/ 07/
C/: third leve where each subdirectory from B/ (01/ or 02/ or 03/ or 04/ or 05/ or 06/ or 07/) contains up to three subdirectories
001/ 002/ 003/
It's at 001/ 002/ 003/ that l want to retrieve files :
My tree is as follow : A/B/C/01/001/files.txt
How can l access that ?
What l have tried ?
for root, dirs,files in sorted(os.walk(path+ "/", topdown=False)): # root
for lab in dirs: # level 1
new_path=path+category+'/'+lab+'/'
for ro,dir,f in os.walk(new_path): #level 2
for dr in dir:
for ri, dir, file in os.walk(new_path+'/'+dr): #level 3
os.chdir(new_path+'/'+dr)
text_file=glob.glob("*.txt")
Is there any efficient way to do that avoiding 5 nested for loops ?
Upvotes: 0
Views: 269
Reputation:
This alone when I try works for me
import os
path = r'C:\root'
for root, dirs,files in os.walk(path): # root
for f in files:
print(f)
This outputs all files on level 3. Which is essentially files contained in the three subdirectories 001/ 002/ 003/ from each of the 7 directories on level B.
Upvotes: 2