The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Question
01:03 Accepted answer (Score 15)
01:22 Answer 2 (Score 6)
01:33 Answer 3 (Score 6)
01:53 Thank you

--

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

Accepted answer links:
[any]: http://docs.python.org/library/functions...
[generator expression]: http://en.wikipedia.org/wiki/Python_synt...

--

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'