user1442957
user1442957

Reputation: 7719

python iterate through list by string matching

I have a list of strings and if the string in my list appears in the filename then I want python to open the file. The catch is, I want python to open the files in the order the string appears in my list. My current code opens the files in the order python wants and only checks if the string in the list appears in the filename.

files

dogs.html
cats.html
fish.html

python

list = ['fi', 'do', 'ca']
for name in glob.glob('*.html'):
  for item in list:
    if item in name:
      with open(name) as k:

Upvotes: 1

Views: 5325

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

lis = ['fi', 'do', 'ca']

for item in lis:
   for name in glob.glob('*.html'):
      if item in name:
         with open(name) as k:

or create a list of all files first, and then filter that list with every iteration of list:

>>> names=glob.glob('*.html')
>>> lis=['fi','do','ca']
>>> for item in lis:
...    for name in filter(lambda x:item in x,names):
...         with open('name') as k:

Upvotes: 3

Bakuriu
Bakuriu

Reputation: 101959

I would do something like this:

filenames = glob.glob('*.html')

for my_string in my_strings:
    for fname in (filename for filename in filenames if my_string in filename):
        with open(fname) as fobj:
            #do something.

Upvotes: 0

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

You can do it a bit simpler by repeating the glob calls:

names = ['fi', 'do', 'ca']
patterns = [s + "*.html" for s in names]

for pattern in patterns:
    for fn in glob.glob(pattern):
        with open(name) as k:
            pass

You can factor out the repeated file system access by using os.listdir and glob.fnmatch, in case you process thousands of files.

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120516

You can create a set of matches:

matching_glob = set([name for name in glob.glob('*.html')])

and then filter your list

list_matching_glob = filter (lambda el: el in matching_glob) filter

Upvotes: 0

Related Questions