搜索多行字符串的目录

时间:2016-02-03 12:45:37

标签: python

寻找一种递归搜索存储库以查找包含多行字符串的所有文件并返回包含多行字符串的文件名的方法。这段只是一个大约30行的标题。

以下是我正在采取但不起作用的方法。

repo = os.getcwd()

header = """ /*
             /* .......paragraph
             /* ..............
             */
         """

for file in glob.glob(repo):
    with open(file) as f:
        contents = f.read()
    if header in contents:
        print file

我收到此错误:

IOError: [Errno 21] Is a directory: '/home/test/python/repos/projects/one'

编辑新版@zondo

def findAllFiles(directory):
    gen = os.walk(directory)
    next(gen)
    return [os.path.join(path, f) for path, _, files in gen for f in files]

def main():
    print "Searching directory for copyright header"
    for file in findAllFiles(repo):
        with open(file) as f:
            contents = f.read()
    if header in contents:
        print file

2 个答案:

答案 0 :(得分:1)

使用os模块,您可以执行以下操作:

# Find not only all files in a folder, but all files in all sub-directories
def find_all_files(folder):
    return [os.path.join(path, f) for path, _, files in os.walk(folder) for f in files]

for file in find_all_files(repo):
    with open(file) as f:
        contents = f.read()
        if header in contents:
            print file

答案 1 :(得分:0)

尝试使用subprocess和pcregrep匹配不同目录中的多行。

from subprocess import call
call(["pcregrep", "-rM","<regular_exp>","<path to directory>"])

从未尝试过这个。我突然想到了