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)
但它很慢。有没有更好的解决办法?谢谢!
您可以使用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)
| 归档时间: |
|
| 查看次数: |
6852 次 |
| 最近记录: |