关于Lua中如何遍历指定文件路径下的所有文件,需要用到Lua的lfs库。
require("lfs")
然后需要用到lfs库中的lfs.dir()方法和lfs.attributes()方法。下面是关于这两个函数的介绍:
lfs.dir(path)
Lua迭代器遍历给定目录的条目。每次调用迭代器时,它都会返回带有目录条目的字符串。 nil
没有更多条目时返回。如果path
不是目录,则会引发错误 。
lfs.attributes(path)
返回filepath的各种属性,包括文件类型、大小、权限、最后访问时间等等信息。
require("lfs")
--读取路径
local path ="C:/Users/Desktop/new/src"
--写入文件
local wFlie = io.open("C:/Users/Desktop/new/code.txt" ,"a")
function writeToFile(path)
local file = io.open(path,"r")
for line in file:lines() do
wFlie:write(line.."\n")
end
file:close()
end
function attrdir(path)
for file in lfs.dir(path) do
--过滤"."和".."目录
if file ~= "." and file ~= ".." then
local f = path.. '/' ..file
local attr = lfs.attributes (f)
--如果是是目录,就递归调用,否则就写入文件
if attr.mode == "directory" then
attrdir(f)
else
wFlie:write(file.."\n")
writeToFile(f)
end
end
end
end
attrdir(path)
wFlie:close()
运行完后生成code.txt文件