Python:如何获取目录中的第一个文件?

tnq*_*177 2 python python-2.7 listdir

所以我想在Python中抓取目录下的第一个文件。我知道我可以这样做:

first_file = [join(path, f) for f in os.listdir(path) if isfile(join(path, f))][0]
Run Code Online (Sandbox Code Playgroud)

但它很慢。有没有更好的解决办法?谢谢!

ale*_*cxe 6

您可以使用next()

first_file = next(join(path, f) for f in os.listdir(path) if isfile(join(path, f)))
Run Code Online (Sandbox Code Playgroud)

请注意,如果目录中没有文件,它将抛出StopIteration异常。要么处理它,要么提供一个默认值

first_file = next((join(path, f) for f in os.listdir(path) if isfile(join(path, f))), 
                  "default value here")
Run Code Online (Sandbox Code Playgroud)

  • @tnq177 在你的情况下,你首先形成一个完整的文件列表,然后得到第一个结果。在这种情况下,迭代器构建仅前进一次。您可能还需要查看 `glob.iglob` 并尝试将其与 `next` 一起使用:像 `next(glob.iglob(join(path, ".*")))` 一样。 (2认同)