Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

I'm writing a Python script that goes through a directory and gathers certain files, but there are a number of files I want excluded that all start the same.

Example code:

for name in files:
   if name != "doc1.html" and name != "doc2.html" and name != "doc3.html":
      print name

Let's say there are 100 hundred HTML files in the directory all beginning with 'doc'. What would be the easiest way to exclude them?

Sorry I'm new to Python, I know this is probably basic.

Thanks in advance.

like image 394
Ruth Avatar asked Feb 03 '10 16:02

Ruth


2 Answers

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.

like image 55
Nadia Alramli Avatar answered Nov 15 '22 15:11

Nadia Alramli


for name in files:
    if not name.startswith("doc"):
        print name
like image 32
Karmic Coder Avatar answered Nov 15 '22 14:11

Karmic Coder