reddy
reddy

Reputation: 1821

To check if filename has substring of a word in a list

I have a list of keywords and I want to go through a directory looking for filename that contain the keyword. If found, binds the matching keyword and file path to a dictionary.

keywords = ['mon', 'tue', 'wed']
dict = {}

directory = os.fsencode(r"my_dir")

for file in os.listdir(directory):
  filename = os.fsdecode(file)
  ext = Path(file).suffix

  if filename in keywords:
    filepath = os.path.join(directory, filename, ext)
    dict[keyword] = filepath

So at the end I want something like this:

{'mon': 'F:\mon_001.txt', 'tue': 'F:\tue_999.txt', 'wed': 'F\wed_123.txt'}

Now how do I find the match?

Upvotes: 0

Views: 9632

Answers (2)

zwer
zwer

Reputation: 25779

You're making this more complicated than it needs to be:

import os

keywords = ['mon', 'tue', 'wed']

directory = "my_dir"

result = {}  # dict store our results

for filename in os.listdir(directory):
    for keyword in keywords:
        if keyword in filename:
            result[keyword] = os.path.join(directory, filename)

This doesn't handle duplicates, however. If you want to store all matching filenames just initialize result as collections.defaultdict(list) and then when setting the found keyword use: result[keyword].append(os.path.join(directory, filename))

Upvotes: 5

Óscar López
Óscar López

Reputation: 235994

There isn't a nice one-liner for this case, because you need to know which keyword matched. An explicit loop is your best bet:

for file in os.listdir(directory):
    filename = os.fsdecode(file)
    ext = Path(file).suffix
    for keyword in keywords:
      if keyword in filename: # this tests for substrings
        filepath = os.path.join(directory, filename, ext)
        dict[keyword] = filepath
        break

Upvotes: 1

Related Questions