Newbie: Joining Lists

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu May 17 06:52:38 EDT 2007


In <1179395397.157566.209330 at l77g2000hsb.googlegroups.com>, mosscliffe
wrote:

> ----------------------- CODE ----------------------
> import os
> import glob
> 
> filenames = []
> patterns = ('.\\t*.py', '.\\*.c??', '.\\*.txt') #  Can these patterns
> for glob processing be specified in the glob call *****ONE****
> for pattern in patterns:
>     filenames = filenames + glob.glob(pattern)   # Is there a better
> way for this line in joining lists *****TWO****

You can `extend()` the list instead of creating new concatenated copies in
each iteration.

> Ps  \\ is because I needed to get the path element for my test and
> windoze does not return a path element  if in current directory

Maybe using `os.path.abspath()` on the file names is a more portable and
robust solution here.

If you don't need all the functionality of `glob.glob()` you can write a
simple function that takes multiple file name patterns:

import fnmatch
import os
import re

def multiglob(patterns):
    pattern_re = re.compile('|'.join(map(fnmatch.translate, patterns)))
    return [os.path.abspath(path)
            for path in os.listdir('.')
            if pattern_re.match(path)]

This lacks `glob.glob()`\s special handling of patterns containing
directory names though.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list