简体   繁体   中英

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:
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:

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM