How to list folders / directories containing specific template files in them in python?

For example, if the file contains the extension .parq, I must specify all the directories present in the folder:

  • /a/b/c/
  • /a/b/e/
  • /a/b/f/

Here I have to specify the directories , , which have a certain template files. cef

+6
source share
1 answer

You can use os.walk to move through all files and directories. Then you can perform a simple pattern matching in the file names (for example, the example you asked in the question).

import os

for path, subdirs, files in os.walk('.'): #Traverse the current directory
    for name in files:
        if '.parq' in name:  #Check for pattern in the file name
            print path

, , . , os.path.join

os.path.join(path, name)

, , .

import os

for path, subdirs, files in os.walk('.'):
    for name in files:
        with open(name) as f:
            #Process the file line by line  
            for line in f:       
                if 'parq' in line:
                    #If pattern is found in file print the path and file   
                    print 'Pattern found in directory %s' %path,
                    print 'in file %s' %name
                    break
+5

All Articles