In python, how do I exclude files from a loop if they begin with a specific set of letters?

if not name.startswith('doc'):
     print name

If you have more prefixes to exclude you can even do this:

if not name.startswith(('prefix', 'another', 'yetanother')):
     print name

startswith can accept a tuple of prefixes.


for name in files:
    if not name.startswith("doc"):
        print name

If you find functional programming matches your style better, Python makes it simple to filter lists with the filter() function:

>>> files = ["doc1.html", "doc2.html", "doc3.html", "index.html", "image.jpeg"]
>>> filter_function = lambda name: not name.startswith("doc")
>>> filter(filter_function, files)
['index.html', 'image.jpeg']

Also take a look at apply(), map(), reduce(), and zip().

Tags:

Python

String