首页 > 解决方案 > 检查文件路径列表是否存在

问题描述

我有一个文件路径列表。我需要检查列表中哪些文件存在,哪些不存在。我想删除不存在的路径。我知道我可以使用 os.path.exists() 或 os.path.isfile() 但对于这些我需要运行一个 for 循环并检查列表中的每个路径。在python中有没有更好的方法来做到这一点?

标签: pythonlist

解决方案


我假设您正在尝试从列表中删除文件而不是从操作系统中

您可以通过列表理解来做到这一点:

files = [...] # list of file paths

files = [path for path in files if os.path.exists(path)]

推荐阅读