2017-07-27 5 views

答えて

5

os.walkを使用すると、すべてのファイルとディレクトリを走査できます。次に、ファイル名に単純なパターンマッチングを実行することができます(質問の例のように)。

import os 

for path, subdirs, files in os.walk('.'): #Traverse the current directory 
    for name in files: 
     if '.parq' in name: #Check for pattern in the file name 
      print path 

必要に応じて後で使用するために、パスをリストに追加することもできます。あなたは完全なファイル名にアクセスしたい場合は、os.path.join

os.path.join(path, name) 

を使用することができますが、ファイル内のパターンにアクセスしたい場合は、以下のようにコードを変更することができます。

import os 

for path, subdirs, files in os.walk('.'): 
    for name in files: 
     with open(name) as f: 
      #Process the file line by line 
      for line in f:  
       if 'parq' in line: 
        #If pattern is found in file print the path and file 
        print 'Pattern found in directory %s' %path, 
        print 'in file %s' %name 
        break 
+0

回答ありがとうございました –

+0

ようこそ!お力になれて、嬉しいです :) –

関連する問題