Removing objects in a list via a wild card

Karthik Gurusamy kar1107 at gmail.com
Wed Sep 19 16:29:22 EDT 2007


On Sep 19, 1:11 pm, David <wizza... at gmail.com> wrote:
> On 9/19/07, James Matthews <nytrok... at gmail.com> wrote:
>
> > Hi List
>
> > I have a list of files from my current directory:
>
> > import os
>
> > files = os.listdir(os.getcwd())
>
> > Now this list also includes some files that i don't want like my python
> > files... How would i remove them
>
> You can use regular expressions:
>
> import re
> files=[file for file in os.listdir(os.getcwd()) if not
> re.match('^.+\.((py)|(pyc))$', file)]
>
> You can also use fnmatch:
>
> from fnmatch import fnmatch
> files = [file for file in os.listdir(os.getcwd()) if not fnmatch(file,
> '*.py') and not fnmatch(file, '*.pyc')]

Another option is to use glob.

import glob

p1 = glob.glob('*.py')
p2 = glob.glob('*.pyc')
all = glob.glob('*')              # won't include '.', '..'

non_py = set(all) - set(p1) - set(p2)

Karthik




More information about the Python-list mailing list