Python: how to get the first file in directory?

こ雲淡風輕ζ 提交于 2019-12-07 21:05:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!