Nips
Nips

Reputation: 13870

How to get numbers from filenames?

I have many files in directory according to the key:

pic001.jpg
pic002.jpg
pic012.jpg
[...]
ico001.jpg
ico002.jpg
ico012.jpg
[...]

and I want to list this files and create structure like this:

for r,d,f in os.walk(directory):
    for file in f:
        if file.startswith("pic"):
            pic = file
            ico = ???
            images_list.append({
                'big': directory + '/' + pic,
                'thumb': directory + '/' + ico,
            })

How to get "pic" file and "ico" assigned to him (only if ico exist)?

Upvotes: 2

Views: 94

Answers (3)

cerkiewny
cerkiewny

Reputation: 2851

Why not use regexp?

import re
...   
m = re.search('\d+', f.name)
print 'ico' + str(m.group(0)) + 'jpg'

Upvotes: 0

Jordan Jambazov
Jordan Jambazov

Reputation: 3620

You can do it using a regular expression.

import re
icon = 'ico%s.jpg' % re.findall(r'^pic(\d+).jpg$', file)[0]

It's definitely going to be more intuitive and easier to maintain than using slices.

Upvotes: 1

stepank
stepank

Reputation: 456

the simplest answer seems to be:

ico = 'ico' + file[3:]

Upvotes: 5

Related Questions