简体   繁体   English

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

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

New to Python and programming. Python 和编程的新手。 I'm using a Mac Air w/ OS X Yosemite version 10.10.2.我使用的是带有 OS X Yosemite 10.10.2 版的 Mac Air。

I'm looking for a way to recursively find multiple subfolders, with the same name(eg"Table"), without using a direct path(assuming I don't know what folders they might be in) and read the files within them using regular expressions or Python.我正在寻找一种方法来递归查找多个具有相同名称(例如“表”)的子文件夹,而不使用直接路径(假设我不知道它们可能在哪些文件夹中)并使用读取其中的文件正则表达式或 Python。 Thank you in advance!先感谢您!

 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()

You can use os.walk , which comes shippes with python for this purpose.为此,您可以使用os.walk ,它随 python 一起提供。 As, the name suggest, os.walk will 'walk' thru your directory recursively and return the root, the dir and a list of file found in the dir.顾名思义, os.walk将“遍历”您的目录并返回根目录、目录和目录中找到的文件列表。

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

You will find an example in the link that I gave above.你会在我上面给出的链接中找到一个例子。

Hence for your example, you can achieve your goal you consider doing an os.walk, set up a regex to match folders with a given pattern and get the file with the matching name in your list of file.因此,对于您的示例,您可以实现您考虑执行 os.walk 的目标,设置正则表达式以匹配具有给定模式的文件夹,并在文件列表中获取具有匹配名称的文件。

For instanxe :例如:

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

the above example will find your wanted file names in a particular folder.上面的示例将在特定文件夹中找到您想要的文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM