如何将os.walk和endswith的匹配结果定向写入指定数组
嘿,这个问题我熟!其实核心就是把「匹配规则」和「目标数组」做绑定,遍历的时候根据匹配结果定向归类就行,给你详细说下怎么做:
核心思路
先提前把你需要的匹配规则和对应的目标数组做一一映射,这样遍历到每个文件/文件夹时,只要检查它符合哪个规则,就把它塞进对应的数组里就行。这种方式扩展性还很强,后面要加新的匹配规则,直接加映射就行。
代码示例(Python版)
比如你要区分TXT文件、Python文件和名为docs的文件夹,代码可以这么写:
import os # 第一步:定义匹配规则和对应数组的映射 # 键是数组名称,值是判断是否匹配的函数 match_config = { "txt_files": lambda path: path.endswith(".txt") and os.path.isfile(path), "py_files": lambda path: path.endswith(".py") and os.path.isfile(path), "docs_folders": lambda path: os.path.basename(path) == "docs" and os.path.isdir(path) } # 初始化所有目标数组 result_arrays = {key: [] for key in match_config.keys()} # 第二步:遍历文件夹及子文件夹 target_root = "/你要遍历的根目录路径" for root, dirs, files in os.walk(target_root): # 先处理文件夹 for dir_name in dirs: dir_path = os.path.join(root, dir_name) # 检查当前文件夹符合哪个规则 for array_name, match_func in match_config.items(): if match_func(dir_path): result_arrays[array_name].append(dir_path) # 如果一个条目只需要匹配一个规则,这里可以加break停止检查 # 再处理文件 for file_name in files: file_path = os.path.join(root, file_name) for array_name, match_func in match_config.items(): if match_func(file_path): result_arrays[array_name].append(file_path) # 第三步:查看结果 print("所有TXT文件:", result_arrays["txt_files"]) print("所有Python文件:", result_arrays["py_files"]) print("所有docs文件夹:", result_arrays["docs_folders"])
代码示例(Node.js版)
如果是用Node.js做文件遍历,逻辑是一样的:
const fs = require('fs').promises; const path = require('path'); async function classifyFilesAndFolders(rootDir) { // 初始化目标数组和匹配规则 const resultArrays = { txtFiles: [], jsFiles: [], imageFolders: [] }; const matchRules = { txtFiles: (fullPath) => path.extname(fullPath) === '.txt', jsFiles: (fullPath) => path.extname(fullPath) === '.js', imageFolders: async (fullPath) => { const stats = await fs.stat(fullPath); return stats.isDirectory() && path.basename(fullPath) === 'images'; } }; // 递归遍历函数 async function traverse(currentDir) { const entries = await fs.readdir(currentDir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(currentDir, entry.name); if (entry.isDirectory()) { // 检查文件夹匹配规则 for (const [arrayName, rule] of Object.entries(matchRules)) { if (await rule(fullPath)) { resultArrays[arrayName].push(fullPath); } } await traverse(fullPath); } else { // 检查文件匹配规则 for (const [arrayName, rule] of Object.entries(matchRules)) { if (rule(fullPath)) { resultArrays[arrayName].push(fullPath); } } } } } await traverse(rootDir); return resultArrays; } // 调用示例 classifyFilesAndFolders('./你的目标目录') .then(results => { console.log('TXT文件列表:', results.txtFiles); console.log('JS文件列表:', results.jsFiles); console.log('图片文件夹列表:', results.imageFolders); }) .catch(err => console.error('遍历出错:', err));
注意事项
- 如果某个文件/文件夹可能符合多个规则,会被加入多个数组;如果需要每个条目只归属一个数组,匹配到第一个符合的规则后加
break就行。 - 写匹配规则时最好明确区分文件和文件夹,避免把文件夹误判成文件(比如上面示例里的
os.path.isfile/stats.isDirectory判断)。 - 遍历大目录时,优先用异步方法(比如Node.js的
fs.promises),避免阻塞主线程。
内容的提问来源于stack exchange,提问作者rNOde
相关产品推荐
相关产品推荐

