Saturday, July 31, 2010

python: using the glob module to perform simple wildcard expansion on a filesystem

import glob
glob.glob('c:\\music\\_singles\\*.mp3')

['c:\\music\\_singles\\a_time_long_forgotten_con.mp3',
'c:\\music\\_singles\\hellraiser.mp3',
'c:\\music\\_singles\\kairo.mp3',
'c:\\music\\_singles\\long_way_home1.mp3',
'c:\\music\\_singles\\sidewinder.mp3',
'c:\\music\\_singles\\spinning.mp3']
glob.glob('c:\\music\\_singles\\s*.mp3')

['c:\\music\\_singles\\sidewinder.mp3',
'c:\\music\\_singles\\spinning.mp3']



You can get a list of all of those with a single call to glob, by using two wildcards at once. One wildcard is the "*.mp3" (to match .mp3 files), and one wildcard is within the directory path itself, to match any subdirectory within "c:\music" like this:



glob.glob('c:\\music\\*\\*.mp3')



source

No comments: