Search code examples
pythonpython-2.7listdir

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!


Solution

  • 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")