Removing objects in a list via a wild card

David wizzardx at gmail.com
Wed Sep 19 16:11:08 EDT 2007


On 9/19/07, James Matthews <nytrokiss 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')]



More information about the Python-list mailing list