user2080223
user2080223

Reputation:

Looping through file names more than necessary

I have the following code:

if inputFileName: 
    if inputFileName.lower().endswith(mediaExt):
        for word in ignoreWords:
            if word not in inputFileName.lower():
                if os.path.isfile(inputDirectory):
                    try:
                        processFile(fileAction, inputDirectory, outputDestination)
                    except Exception, e:
                        logging.error(loggerHeader + "There was an error when trying to process file: %s", os.path.join(inputDirectory, inputFileName))
                        logging.exception(e)
                else:
                    try:
                        processFile(fileAction, os.path.join(inputDirectory, inputFileName), outputDestination)
                    except Exception, e:
                        logging.error(loggerHeader + "There was an error when trying to process file: %s", os.path.join(inputDirectory, inputFileName))
                        logging.exception(e)

ignoreWords is a list containing a few words that I don't want a filename to contain. Now my issue is this will loop through the same file for x items in my list. I'd like it to only match the words once (or run processFile once when matching is done) but not quite able to find a proper solution to it

Upvotes: 1

Views: 72

Answers (2)

kiriloff
kiriloff

Reputation: 26335

You should loop on filenames. If filename is not in your ignoreWords list, you do discard it.

      if inputFileName: 
            if inputFileName.lower().endswith(mediaExt):
                for word in inputFileName.lower():
                    if word not in ignoreList:
                        if os.path.isfile(inputDirectory):
                            try:
                                processFile(fileAction, inputDirectory, outputDestination)
                            except Exception, e:
                                logging.error(loggerHeader + "There was an error when trying to process file: %s", os.path.join(inputDirectory, inputFileName))
                                logging.exception(e)
                        else:
                            try:
                                processFile(fileAction, os.path.join(inputDirectory, inputFileName), outputDestination)
                            except Exception, e:
                                logging.error(loggerHeader + "There was an error when trying to process file: %s", os.path.join(inputDirectory, inputFileName))
                                logging.exception(e)

Upvotes: 0

eumiro
eumiro

Reputation: 212835

Replace

for word in ignoreWords:
    if word not in inputFileName.lower():

with

if not any(word in inputFileName.lower() for word in ignoreWords):

Upvotes: 1

Related Questions