Andreas N
Andreas N

Reputation: 834

How to match a python formatstring to elements in a list?

I use Python and there's a list of file names of different file types. Text files may look like these:

01.txt
02.txt
03.txt
...

Let's assume the text files are all numbered in this manner. Now I want to get all the text files with the number ranging from 1 to 25. So I would like to provide a formatstring like %02i.txt via GUI in order to identify all the matching file names.

My solution so far is a nested for loop. The outer loop iterates over the whole list and the inner loop counts from 1 to 25 for every file:

fmt = '%02i.txt'
for f in files:
    for i in range(1, 25+1):
        if f == fmt % i:
            # do stuff

This nested loop doesn't look very pretty and the complexity is O(n²). So it could take a while on very long lists. Is there a smarter/pythonic way of doing this?

Well, yes, I could use a regular expression like ^\d{2}\.txt$, but a formatstring with % is way easier to type.

Upvotes: 2

Views: 96

Answers (2)

jamylak
jamylak

Reputation: 133574

A more pythonic way to iterate through files is through use of the glob module.

>>> import glob
>>> for f in glob.iglob('[0-9][0-9].txt'):
        print f


01.txt
02.txt
03.txt

Upvotes: 0

HYRY
HYRY

Reputation: 97301

You can use a set:

fmt = '%02i.txt'
targets = {fmt % i for i in range(1, 25+1)}

then

for f in files:
    if f in targets:
        # do stuff

Upvotes: 2

Related Questions