Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to get the first file in directory?

So I want to grab the first file under a directory in Python. I know I can do like this:

first_file = [join(path, f) for f in os.listdir(path) if isfile(join(path, f))][0]

But it's slow. Is there any better solution? Thanks!

like image 274
tnq177 Avatar asked Sep 14 '25 02:09

tnq177


1 Answers

You can use next():

first_file = next(join(path, f) for f in os.listdir(path) if isfile(join(path, f)))

Note that if there are no files in the directory it would throw StopIteration exception. Either handle it, or provide a default value:

first_file = next((join(path, f) for f in os.listdir(path) if isfile(join(path, f))), 
                  "default value here")
like image 57
alecxe Avatar answered Sep 16 '25 15:09

alecxe