[英]How do I recursively find a specific subfolder name in a directory using Python / Regular expressions?
Python 和编程的新手。 我使用的是带有 OS X Yosemite 10.10.2 版的 Mac Air。
我正在寻找一种方法来递归查找多个具有相同名称(例如“表”)的子文件夹,而不使用直接路径(假设我不知道它们可能在哪些文件夹中)并使用读取其中的文件正则表达式或 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
将“遍历”您的目录并返回根目录、目录和目录中找到的文件列表。
http://www.tutorialspoint.com/python/os_walk.htm
你会在我上面给出的链接中找到一个例子。
因此,对于您的示例,您可以实现您考虑执行 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
上面的示例将在特定文件夹中找到您想要的文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.