The pathlib module exists since 3.4.
It gives you a better abstraction.
Written as a generator:
def find_by_ext(root, suffix):
for root, dirs, files in os.walk(root):
for file in files:
path = pathlib.Path(root, file)
if path.suffix == suffix:
yield path
The argument root is the start point.
Suffix should be '.html' in your case.
The generator returns for each iteration a Path object.
To get the same behaviour, you can write a second function, which is
iterating over the generator:
def open_all_html(root):
for file in find_by_ext(root, '.html'):
try:
data = file.open('r', encoding='utf-8', errors='ignore')
except Exception as error:
print('Could not open file {}. Error: {}'.format(file, error))
else:
print('Successfully opened file {}.'.format(file))
# normally you do something with the data
# this can also be put into a extra function
Calling it:
open_all_html('Downloads/')
Output:
Successfully opened file Downloads/asterisk-15.2.2/asterisk-15.2.2-summary.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjmedia/docs/footer.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjmedia/docs/header.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjnath/docs/footer.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjnath/docs/header.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjlib-util/docs/footer.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjlib-util/docs/header.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjsip/docs/footer.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjsip/docs/header.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjlib/docs/footer.html.
Successfully opened file Downloads/asterisk-15.2.2/third-party/pjproject/source/pjlib/docs/header.html.
Successfully opened file Downloads/asterisk-15.2.2/static-http/mantest.html.
Successfully opened file Downloads/asterisk-15.2.2/static-http/ajamdemo.html.
Successfully opened file Downloads/skyradar-gui/ui/index.html.