Basj
Basj

Reputation: 46493

Indexed list of files in a folder that match a criteria

I'm trying to list all files in a folder that match MySample %i %j.wav (where %i, %j should be integers), but instead of having the result like this (I tried glob.glob('MySample *.wav')):

["MySample 117 12.wav", "MySample 011 18.wav", "MySample 13 45.wav"]

I would like to have something that would be indexed by the patterns variable %i, %j :

{(117, 12): "MySample 117 12.wav", 
 (11, 18): "MySample 011 18.wav", 
 (13, 45) : "MySample 13 45.wav"}

Upvotes: 0

Views: 100

Answers (2)

Bruce
Bruce

Reputation: 7132

You can use a regexp to match

import re

def getKey(x):
  m=re.match ('MySample (\d+) (\d+).wav',x)                                                                                                                                                                     
  if m:
    return (m.group(1),m.group(2))                                                                                                                                                                              
  else:
    return None

sample=["MySample 117 12.wav", "MySample 011 18.wav", "MySample 13 45.wav"]

Then a list comprehension to create the dictionary

r=dict(((getKey(x),x) for x in sample))

Upvotes: 0

JLDiaz
JLDiaz

Reputation: 1443

It is rather straightforward using regexps:

import os, re


samples = {}
for f in os.listdir("."):
    m = re.match(r"MySample (\d+) (\d+).wav", f)
    if m:
        samples[tuple(int(x) for x in m.groups())] = f

Upvotes: 2

Related Questions