2017-04-25 1 views
2

私は、ディレクトリ内のrepository.configファイルの最初の表示を取得し、サブディレクトリの検索を停止する必要があります。os.walk最初に見つかった後にサブディレクトリを探すのをやめてください

 
./WAS80/base/disk1/ad/repository.config 
./WAS80/base/disk1/md/repository.config 
./WAS80/base/disk2/ad/repository.config 
./WAS80/base/disk3/ad/repository.config 
./WAS80/base/disk4/ad/repository.config 
./WAS80/base/repository.config 
./WAS80/fixpack/fp5/repository.config 
./WAS80/fixpack_suplements/fp5/repository.config 
./WAS80/supplements/disk1/ad/repository.config 
./WAS80/supplements/disk1/md/repository.config 
./WAS80/supplements/disk2/ad/repository.config 
./WAS80/supplements/disk3/ad/repository.config 
./WAS80/supplements/disk4/ad/repository.config 
./WAS80/supplements/repository.config 

私は太字のものを必要とし、サブディレクトリに探して停止します。

は、ここに私のディレクトリツリーです。

私はこのコードを試し始めましたが、わかりませんでした。

pattern='repository.config' 
path='/opt/was_binaries' 

    def find_all(name, path): 
      result = [] 
      for root, dirs, files in os.walk(path): 
        if name in files: 
          result.append(os.path.join(root, name)) 
          continue 

      return result 
+0

適切にあなたのコード一つのインデントのために。 Pythonはスペースに非常に敏感です。別のものについては、 "基本的に"あなたの段落を開始しないでください。 –

+0

「私はこのコードを試し始めましたが、わかりませんでした」平均?あなたが気に入らない、または理解していないことは何をしていますか?具体的にしてください。コメントに返信しないでください!あなたの質問を編集して、独立した問題の声明にしてください。 –

答えて

4

これは、あなたが欲しいものを行う必要があります。

import os 

res = [] 

for here, dirs, files in os.walk(startdir, topdown=True): 
    if 'repository.config' in files: 
     res.append(os.path.join(here, 'repository.config')) 
     dirs[:] = [] 

print(res) 

あなたが'repository.config'ファイルに遭遇するたびに、そのディレクトリツリーにさらに下降からos.walkを防ぐために[]dirsを設定します。

2

まず、あなたはとても親ディレクトリが前に子ディレクトリをスキャンしている(これはデフォルトです)topdownTrueに設定されていることを確認する必要があります。

existingset()を作成して、設定ファイルが正常に見つかったときに通過したディレクトリを覚えておいてください。

その後、あなたはリストであなたのファイル名を見つけたとき:

  • チェックファイルのディレクトリは、ディレクトリの子でない場合は、
  • を登録し、それがない場合は、単にパスを書き留めのファイルの場合、path\to\dirがすでにsetに入っていても、ex:path\to\dir2をスキャンする必要がありますが、path\to\dir\subdirは正常に除外されます)。

コード:

import os 

existing = set() 
for root,dirs,files in os.walk(path,topdown=True): 
    if any(root.startswith(r) for r in existing): 
     # current directory is longest and contains a previously added directory: skip 
     continue 
    if "repository.config" in files: 
     # ok, we note down root dir (+ os.sep to avoid filtering siblings) and print the result 
     existing.add(root+os.sep) 
     print(os.path.join(root,"repository.config")) 
関連する問題