2016-07-12 8 views
0

(Python 2.7) 以下のコードは、ディレクトリで.xmlファイルを検索し、各XML内の文字列を検索します。 .xmlファイルが見つからない(または開かれている)ときに例外を取得しようとしています。Python forループでIOErrorを除いて 'open()'を試してください

XMLが見つからない場合、 'with'ステートメントは正しく実行されませんが、 'IOError'を除いて無視され、その前に進みます。

import os 

for root, dirs, files in os.walk('/DIRECTORY PATH HERE'): 
    for file1 in files: 
     if file1.endswith(".xml") and not file1.startswith("."): 
      filePath = os.path.join(root, file1) 

      try: 
       with open(filePath) as f: 
        content = f.readlines() 
       for a in content: 
        if "string" in a: 
         stringOutput = a.strip() 
         print 'i\'m here' + stringOutput 

      except IOError: 
       print 'No xmls found' 
+0

IOError例外を無視しても、プログラムでIOError例外が発生しますか? – purrogrammer

+0

いいえ、IOError以外の方法を見つけることができません – bzzWomp

+0

ファイル* do *が存在する可能性がありますが、内容が空であるため、 'for'ループは実行されません。その理由は、XMLファイルをフィルタリングしているため、このシナリオは可能性が高いからです。コンテンツが空であるかどうかを確認し、ファイル名を印刷してテストすることができます。 – purrogrammer

答えて

0

あなたのコメントに基づいて、私はこれがあなたが探しているものだと思います。

import os 

for root, dirs, files in os.walk("/PATH"): 
    if not files: 
     print 'path ' + root + " has no files" 
     continue 

    for file1 in files: 
     if file1.endswith(".xml") and not file1.startswith("."): 
      filePath = os.path.join(root, file1) 

      with open(filePath) as f: 
       content = f.readlines() 

       for a in content: 
        if "string" in a: 
         stringOutput = a.strip() 
         print 'i\'m here' + stringOutput 
     else: 
      print 'No xmls found, but other files do exists !' 
+0

ありがとう – bzzWomp

関連する問題