python - 检查文件路径列表是否存在
问题描述
我有一个文件路径列表。我需要检查列表中哪些文件存在,哪些不存在。我想删除不存在的路径。我知道我可以使用 os.path.exists() 或 os.path.isfile() 但对于这些我需要运行一个 for 循环并检查列表中的每个路径。在python中有没有更好的方法来做到这一点?
解决方案
我假设您正在尝试从列表中删除文件而不是从操作系统中
您可以通过列表理解来做到这一点:
files = [...] # list of file paths
files = [path for path in files if os.path.exists(path)]
推荐阅读
- ios - 当应用程序需要 1 次 4 位登录代码时,如何将应用程序提交到 App Store 审核流程
- javascript - 当组件是联合类型时如何定义类型
- python - 标记表达式
- android - DisplayAlert 不显示按钮
- python - 尝试找出用户的全球平均评分时出现 KeyError
- javascript - 如何在单个有效负载中创建 Mongoose 一对多关系实体?
- kubernetes - kubernetes make error:touch: _output/bin/prerelease-lifecycle-gen: No such file or directory
- ios - 是否可以在 iOS 上的 WKWebView 中访问相机?
- c++ - 同时处理2条消息
- vue.js - Vue中的CKEditor 4 - 如何防止断字?