2016-10-02 20 views
0

名前に特定の文字列を含むファイルをすべて選択するには、Pythonでos.walkメソッドを使いたいと思います。ここでは、コード、私は自分の名前に文字列「ラマン」を含むすべてのファイルを選択するよりも、私は特定の文字列を含むフォルダ内のすべてのパスを選択する関数

func(root, 'Raman') 

を入力すると今

def func(root = root, element = ''): 
    c = [] 
    for path, subdirs, files in os.walk(root): 
     c = c + [ os.path.join(path, name) for name in files \ 
     if element in os.path.join(path, name) ] 
    return c 

を書きました。私は2番目の引数は文字列

func(root, ['string 1', 'string 2', ... 'string n']) 

のリストである機能を持っていると思いますし、それが「文字列1」、「文字列2」..「文字列n」が含まれているすべてのパスを選択しますが、問題はそれよりも難しいです。前のコードの修正を私に提案できる人はいますか?

import os 


def func(root, elements): 
    c = [] 
    for path, subdirs, files in os.walk(root): 
     c = c + [os.path.join(path, name) for name in files \ 
       if any(element in os.path.join(path, name) for element in elements)] 
    return c 

残念ながら、現在の形でfuncが、そのうまく読み取らない:

+0

[glob](https://docs.python.org/2/library/glob.html)を使用してください。 – Ahmad

答えて

1

あなたはany組み込み関数を使用することができます。

def func(root, elements): 
    for root_path, _, files in os.walk(root): 
     for name in files: 
      full_path = os.path.join(root_path, name) 
      if any(element in full_path for element in elements): 
       yield full_path 
+0

その変換の利点は何ですか? –

+0

私はちょうど彼らが私が探しているものをやっていないことに気付きました、私は彼らに['string1'、 'string 2'、...、 'string n'これらのコードは、['string 1'、 'string 2'、... 'string n']のいずれかを含むファイルを選択するように見えます。 –

+0

'any'を' all'に変更してください。 –

関連する問題