In python, how can I check if a filename ends in '.html' or '_files'?

Question:

In python, how can I check if a filename ends in ‘.html’ or ‘_files’?

Asked By: user1434001

||

Answers:

You probably want to know if a file name ends in these strings, not the file istelf:

if file_name.endswith((".html", "_files")):
    # whatever

To test whether a file ends in one of these strings, you can do this:

with open(file_name) as f:
    f.seek(-6, 2)           # only read the last 6 characters of the file
    if f.read().endswith((".html", "_files")):
        # whatever
Answered By: Sven Marnach

This might be a little bit more comprehensive.

dirname = os.getcwd()
file_extension_type = ('.html', '_files') # , '.exe', 'jpg', '...')
 
# iterating over all files
for file in os.listdir(dirname):
    if file.endswith(file_extension_type):
        print("Found a file {}".format(file))  # printing file name of desired extension
    else:
        continue
Answered By: 3kstc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.