Python:如何获取目录中的第一个文件? [英] Python: how to get the first file in directory?

查看:149
本文介绍了Python:如何获取目录中的第一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!

推荐答案

您可以使用 next():

You can use next():

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

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

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

这篇关于Python:如何获取目录中的第一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆