(Python 2.7) The code below searches directories for .xml files and searches for a string within each XML. I am trying to get an exception for when .xml files cannot be found (or opened).
So far when no XML is found, the 'with' statement is correctly not executed but it is ignoring 'except IOError' and proceeding past it.
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'
Based on your comments, I think this is what you are looking for.
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 !'