Lua 標準庫無跨平台目錄遍歷 API,常見做法是 io.popen 調用系統命令 (dir/ls) 獲取文件列表,再逐行處理。本文提供 Windows/Linux 兼容的完整片段,並演示對 .txt 文件逐行檢查列數一致性。
核心代碼
-- 獲取文件列表 (Windows)
local getinfo = io.popen('dir ..\\file /b /s')
local all = getinfo:read('*all')
getinfo:close()
-- 寫入臨時文件供後續讀取 (模擬數據源)
local filenameList = io.open("filename.txt", "wb")
filenameList:write("Path\n")
filenameList:write(all)
filenameList:close()
-- 讀取列表 (假設有 tab.Open 解析 CSV/TSV)
local filenameList = tab.Open([[../filename.txt]], "Path", false)
-- 遍歷處理 .txt 文件
for index, Row in ipairs(filenameList) do
local pathlist = Row["Path"]
local rowString = string.find(pathlist, "%.txt")
if rowString then
moon.CheckRowlength(pathlist, pathlist) -- 自定義檢查函數
end
end
跨平台命令選擇
| 系統 | 命令 | 說明 |
| Windows | dir /b /s | /b 純文件名,/s 遞歸子目錄 |
| Linux/macOS | ls -R 或 find . -type f | -R 遞歸,find 功能更強 |
改進版:純 Lua 遍歷 (LuaFileSystem / lfs)
local lfs = require("lfs")
function traverse(dir, callback)
for entry in lfs.dir(dir) do
if entry ~= "." and entry ~= ".." then
local path = dir .. "/" .. entry
local attr = lfs.attributes(path)
if attr.mode == "directory" then
traverse(path, callback)
elseif attr.mode == "file" then
callback(path, attr)
end
end
end
end
-- 使用
traverse("../file", function(path, attr)
if path:match("%.txt$") then
moon.CheckRowlength(path, path)
end
end)
關鍵對比
| 方案 | 優點 | 缺點 |
| io.popen + 系統命令 | 無依賴、一行命令搞定 | 平台相關、解析文本脆弱、無法獲取元數據 |
| LuaFileSystem (lfs) | 跨平台、豐富屬性 (size, mtime, mode)、類型安全 | 需安裝 C 擴展、部署稍繁瑣 |
實戰建議
- 腳本層面優先用
lfs,健壯性更好。
- 一次性臨時腳本/受限環境可用
io.popen 快速實現。
- 文件名含空格/特殊字符時,
io.popen 解析極易出錯,lfs 無此問題。
選對工具,文件遍歷不再是痛點。
copyright ©
萬盛學電腦網 all rights reserved