在Lua Torch中迭代目录

3
在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个回答

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

0

我需要比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://dev59.com/yU3Sa4cB1Zd3GeqPyMkt#3254007
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接