如何在Boost Build/b2/jam中保留列表中的现有文件路径
过滤文件路径列表中不存在的文件
Python 实现
用列表推导式结合文件存在性判断,简洁高效:
import os # 示例路径列表 file_paths = ["file1.txt", "/path/to/existing/file2.jpg", "non_existent.pdf"] # 过滤所有存在的路径(包含目录) existing_paths = [path for path in file_paths if os.path.exists(path)] # 只保留实际文件,排除目录 existing_files_only = [path for path in file_paths if os.path.isfile(path)] print(existing_files_only)
os.path.exists():检查路径(文件/目录)是否存在os.path.isfile():仅判断是否为普通文件,适合只想保留文件的场景
Bash 实现
遍历路径列表,用条件判断筛选存在的文件:
# 定义路径数组 file_paths=("file1.txt" "/path/to/existing/file2.jpg" "non_existent.pdf") existing_files=() # 逐个检查 for path in "${file_paths[@]}"; do if [ -f "$path" ]; then existing_files+=("$path") fi done # 输出结果 printf "%s\n" "${existing_files[@]}"
-f:判断路径是否为普通文件,换成-e可以包含目录- 注意用引号包裹路径,避免空格导致的错误
Node.js 实现
同步版本(小批量文件)
const fs = require('fs'); const filePaths = ["file1.txt", "/path/to/existing/file2.jpg", "non_existent.pdf"]; const existingFiles = filePaths.filter(path => { try { const stats = fs.statSync(path); return stats.isFile(); // 确保是文件而非目录 } catch (err) { // 路径不存在时捕获异常,返回false return false; } }); console.log(existingFiles);
异步版本(大批量文件,避免阻塞)
const fs = require('fs').promises; async function filterExistingFiles(filePaths) { const checkResults = await Promise.all( filePaths.map(async path => { try { const stats = await fs.stat(path); return stats.isFile() ? path : null; } catch (err) { return null; } }) ); // 过滤掉null值,得到存在的文件路径 return checkResults.filter(item => item !== null); } // 使用示例 const filePaths = ["file1.txt", "/path/to/existing/file2.jpg", "non_existent.pdf"]; filterExistingFiles(filePaths).then(res => console.log(res));
- 用
stat方法可以精确区分文件和目录,比existsSync更严谨 - 异步版本适合处理大量文件,不会阻塞主线程
内容的提问来源于stack exchange,提问作者Gabriel Devillers
相关产品推荐
相关产品推荐

