如何在python中列出包含特定模式文件的文件夹/目录?

Jay*_*aya 6 file python-2.7

例如,如果文件包含扩展名,.parq我必须列出文件夹中存在的所有目录:

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

在这里,我必须列出目录c,e,f它有特定的模式文件.

Moh*_*hif 6

您可以使用os.walk遍历所有文件和目录.然后,您可以在文件名中进行简单的模式匹配(就像您在问题中给出的示例).

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
Run Code Online (Sandbox Code Playgroud)

您可以将路径追加到列表中,以便以后使用它.如果要访问完整文件名,可以使用os.path.join

os.path.join(path, name)
Run Code Online (Sandbox Code Playgroud)

如果要访问文件中的模式,可以按如下方式修改代码.

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
Run Code Online (Sandbox Code Playgroud)