Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if there is a folder with a name that start with a specific string

Tags:

python

I'm writing a python script that is supposed to manage my running files. I want to make sure that the source and target folder exist before I run it and I can do this with os.path.exists. However, I have a set of foldernames runner<i>. Is there a way to check that there is some folders begining with that name?

For example, if in the path /path/to/runners I have at least one folder named runner:

/path/to/runners/ $ ls file1.txt
file2.txt
folder1
folder2
runner1 runner35
zfolder

Then the result is true. Remove runner1 and runner35 and it will be false.

like image 217
Yotam Avatar asked Nov 20 '11 11:11

Yotam


1 Answers

You could do the following:

import os
if any(x.startswith('runner') for x in os.listdir('/path/to/runners')):
    print "At least one entry begins with 'runner'"

That uses the helpful any function and a generator expression.

like image 181
Mark Longair Avatar answered Sep 21 '22 02:09

Mark Longair