2016-07-12 50 views
0

(Python 2.7版) 下面搜索目录以.xml文件和搜索代码每个XML中的字符串。我试图找出.xml文件无法找到(或打开)时的异常。尝试“开放()”,除了IO错误在Python for循环

到目前为止,在没有XML被找到,“用”语句不正确执行,但它无视“除了IO错误”,并继续过去吧。

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

不,我无法找到前往的道路“除了IO错误” – bzzWomp

+0

这可能是文件*做*存在,但内容是空的,所以'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