HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python function to match filenames with extension names

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withmatchfunctionextensionnamespythonfilenames

Problem

I have written a Python function which matches all files in the current directory with a list of extension names. It is working correctly.

import os, sys, time, re, stat

def matchextname(extnames, filename):
    # Need to build the regular expression from the list
    myregstring = ""
    for index in range(len(extnames)):
        # r1 union r2 and  so on operator is pipe(|)
        # $ is to match from the end
        if index <  len(extnames) - 1:
            myregstring =  myregstring + extnames[index] + '

It is called like this:

if __name__ == '__main__':
    fileextensions = ['\.doc', '\.o', '\.out', '\.c', '\.h']
    try:
        currentdir = os.getcwd()
    except OSError:
        print 'Error occured while getting current directory'
        sys.exit(1)
    for myfiles in os.listdir(currentdir):
        matchextname(fileextensions, myfiles)


Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic? + '|' else: myregstring = myregstring + extnames[index] + '

It is called like this:

%%CODEBLOCK_1%%

Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic? # getting regexobject myregexobj = re.compile(myregstring) # Now search searchstat = myregexobj.search(filename) if searchstat: print 'Regex', filename


It is called like this:

%%CODEBLOCK_1%%

Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic?

Solution

.endswith() accepts a tuple:

#!usr/bin/env python
import os

fileextensions = ('.doc', '.o', '.out', '.c', '.h')
for filename in os.listdir(os.curdir):
    if filename.endswith(fileextensions):
       print(filename)

Code Snippets

#!usr/bin/env python
import os

fileextensions = ('.doc', '.o', '.out', '.c', '.h')
for filename in os.listdir(os.curdir):
    if filename.endswith(fileextensions):
       print(filename)

Context

StackExchange Code Review Q#19103, answer score: 7

Revisions (0)

No revisions yet.