在Lua Torch中迭代目录

在 Torch 中,我正在按以下方式遍历包含子文件夹的文件夹:

subfolders = {}
counter = 0

for d in paths.iterdirs(root-directory) do
      counter = counter + 1
      subfolders[counter] = d
      -- 处理子文件夹内容
end

当我打印 subfolders 时,子文件夹似乎是以随机顺序访问的。但我想按名称顺序遍历它们。我该怎么做?谢谢!

点赞
用户4013781
用户4013781

使用以下方式解决:

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
2015-12-19 02:22:42
用户1830334
用户1830334

我需要比Chris的答案更强大的解决方案,它不排除纯文件、父目录(..)或当前目录(.)。我也不确定他的代码中神奇数字447是什么意思。标准的Lua没有一种方法来检查一个文件是否是一个目录,所以这只在Linux/OSX上有效。

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)
2017-08-10 18:05:32