1

この関数(特定の文字列のディレクトリを検索する)ですべてのサブディレクトリも検索するようにしようとしています。これを再帰的に実行します。私はPythonを始めるのに十分な知識がありません。どんなガイダンスも素晴らしいでしょう。

ありがとう!

def grep(regex, base_dir):
    matches = list()
    for filename in os.listdir(base_dir):
        full_filename = os.path.join(base_dir, filename)
        if not os.path.isfile(full_filename):
            continue
        with open(os.path.join(base_dir, filename)) as fh:
            content = fh.read()
            matches = matches + re.findall(regex, content)
    return matches
4

4 に答える 4

2

ディレクトリ全体をクロールする場合は、を試してくださいos.walk()。このようなものは機能する可能性があります(テストされていませんが、機能しない場合は調整できます):

def grep(regex, base_dir):
    matches = list()
    # os.walk() returns a tuple - the directory path, a list of directories and the files
    for dirpath, dirname, files in os.walk(base_dir):
        # Iterate through the directory list, reading the files
        for directory in dirname:
          for filename in os.listdir(directory):
              with open(os.path.join(base_dir, directory, filename)) as fh:
                  content = fh.read()
                  matches = matches + re.findall(regex, content)
    return matches
于 2012-10-25T19:32:12.630 に答える
1

I would use something like this:

def find_file_matches(filename, regex):
    with open(filename, 'rt') as fh:
        return re.findall(regex, fh.read())

def walktree(top):
    """ Walk the directory tree starting from top, and
        yield a tuple of each folder and all the files in it. """
    names = os.listdir(top)
    yield top, (name for name in names if not os.path.isdir(name))
    for name in names:
        if os.path.isdir(name):
            for (newtop, children) in walktree(os.path.join(top, name)):
                yield newtop, children

def grep(regex, base_dir="."):
    matches = []
    for dir, files in walktree(base_dir):
        for file in files:
            filename = os.path.join(dir, file)
            matches.append(find_file_matches(filename, regex))
    return matches
于 2012-10-25T21:18:54.477 に答える
1

再帰的トラバーサルについては、試してくださいos.walk。使用方法については、www.saltycrane.com / blog / 2007/03 /python-oswalk-example/をご覧ください。

于 2012-10-25T19:32:04.487 に答える
-1

コマンドラインから

find . -type d | grep -i nameofdir

または同様のもの。

于 2012-10-25T19:29:47.797 に答える