The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Checking If There Is A Folder With A Name That Start With A Specific String
00:51 Accepted Answer Score 16
01:06 Answer 2 Score 7
01:21 Answer 3 Score 6
01:25 Thank you

--

Full question
https://stackoverflow.com/questions/8201...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 16


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.




ANSWER 2

Score 7


Mark Longair's answer is quite fine, and an (equivalent) alternative for this kind of expression is to use glob:

import glob
if glob.glob('/path/to/runners/runner*'):
    print "At least one entry begins with 'runner'"



ANSWER 3

Score 6


import glob

if glob.glob('/path/to/runners/runner*'):
    print 'condition satisfied'