2

I have a folder ROOT and inside many different folders (let's assume N), that for sake of simplicity I call F1, F2 and so on...

I need to work with the file inside these folders. If I have only one folder I know that I can do:

os.chdir(".") #I'm workingo in ROOT
for filename in glob.glob("*.txt"):
    #I can work with the i-th file...

But what I need to do is something like this (pseudo-code like):

os.chdir(".") #I'm working in ROOT
for F-i-th in ROOT: #for each folder in the ROOT main folder
    for filename in F-i-th("*.txt"): #I select only the file with this extention
         #process data inside i-th file

I mean that I need to go inside the first folder (F1) and process all the file (or if it is possible all the .txt file), after I should go inside the F2 and process all the file....

1
  • 4
    Do you just want os.walk? Commented Nov 5, 2015 at 16:23

1 Answer 1

6

os.walk will perform recursion of a directory and fnmatch.filter will match filename patterns. Simple example:

import os
import fnmatch

for path,dirs,files in os.walk('.'):
    for f in fnmatch.filter(files,'*.txt'):
        fullname = os.path.abspath(os.path.join(path,f))
        print(fullname)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.