如何使用 Python / 正则表达式递归查找目录中的特定子文件夹名称?

How do I recursively find a specific subfolder name in a directory using Python / Regular expressions?

Python 和编程的新手。我使用的是 Mac Air w/ OS X Yosemite 版本 10.10.2。

我正在寻找一种方法来递归查找具有相同名称(例如"Table")的多个子文件夹,而不使用直接路径(假设我不知道它们可能在哪些文件夹中)并使用正则表达式或 Python 读取其中的文件。先感谢您!

import sys
import os, re, sys
import codecs
import glob



files = glob.glob( '*/Table/.*Records.sql' )

with open( 'AllTables1.2.sql', 'w' ) as result:
    for file_ in files:
        print file_
        if len(file_) == 0: continue
        for line in open( file_, 'r' ):
            
            line = re.sub(r'[\[\]]', '', line)
            line = re.sub(r'--.*', '', line)
            line = re.sub('NVARCHAR', 'VARCHAR', line)
            line = re.sub(r'IDENTITY', 'AUTO_INCREMENT', line)
            line = re.sub(r'DEFAULT\D* +','', line)
            line = re.sub(r'\W(1, 1\W)', ' ', line)
        
        
            result.write( line.decode("utf-8-sig"))                 
            

result.close()

您可以使用 os.walk,它与 python 一起提供用于此目的。顾名思义,os.walk 将 'walk' 递归地遍历您的目录,并且 return 根目录、目录和在目录中找到的文件列表。

http://www.tutorialspoint.com/python/os_walk.htm

你会在我上面给出的 link 中找到一个例子。

因此,对于您的示例,您可以实现您考虑执行 os.walk 的目标,设置正则表达式以匹配具有给定模式的文件夹,并在文件列表中获取具有匹配名称的文件。

实例:

import os

for root, dir, filelist in os.walk('./'):
    if dir == 'results': # insert logic to find the folder you want 
        for file in filelist:
            if file  == 'xx': # logic to match file name 
                fullpath = os.path.join(root, file) # Get the full path to the file

以上示例将在特定文件夹中找到您想要的文件名。