迭代Lua Torch中的目录

时间:2015-12-19 01:42:19

标签: loops for-loop lua iterator torch

在Torch中,我正在迭代一个充满子文件夹的文件夹,如下所示:

subfolders = {}
counter = 0

for d in paths.iterdirs(root-directory) do
      counter = counter + 1
      subfolders[counter] = d
      -- do something with the subfolders' contents
end

当我打印子文件夹时,子文件夹似乎是以随机顺序访问的。相反,希望按名称顺序迭代它们。我该怎么做呢?谢谢!

2 个答案:

答案 0 :(得分:2)

使用以下方法解决:

subfolders = {}
counter = 0

local dirs = paths.dir(root-directory)
table.sort(dirs)

for i = 1, 447 do
    counter = counter + 1
    subfolders[counter] = dirs[i]
end

答案 1 :(得分:0)

我需要一个比Chris的答案更强大的解决方案,它不排除普通文件,父目录(.)或当前目录(447)。我也不确定他的代码中的幻数function isSubdir(path) noError, result = pcall(isDir, path) if noError then return result else return false end end -- Credit: https://stackoverflow.com/a/3254007/1830334 function isDir(path) local f = io.open(path, 'r') local ok, err, code = f:read(1) f:close() return code == 21 end function getSubdirs(rootDir) subdirs = {} counter = 0 local dirs = paths.dir(rootDir) table.sort(dirs) for i = 1, #dirs do local dir = dirs[i] if dir ~= nil and dir ~= '.' and dir ~= '..' then local path = rootDir .. '/' .. dir if isSubdir(path) then counter = counter + 1 subdirs[counter] = path end end end return subdirs end local subdirs = getSubdirs('/your/root/path/here') print(subdirs) 是多少。 Standard Lua doesn't have a way to check if a file is a directory,所以这只适用于Linux / OSX。

{{1}}