问题
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!
回答1:
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")
来源:https://stackoverflow.com/questions/35114559/python-how-to-get-the-first-file-in-directory