如何获取Lua中的目录列表

che*_*che 28 lua filenames directory-listing

我需要LUA中的目录列表

假设我有一个目录路径为"C:\ Program Files"

我需要该特定路径中所有文件夹的列表以及如何搜索该列表中的任何特定文件夹.

需要路径"C:\ Program Files"中所有文件夹的列表

以下是上述路径中的文件夹名称

  1. test123
  2. test4567
  3. 文件夹123
  4. 文件夹456
  5. 文件夹456 789

    需要在列表中获得上述内容,然后必须仅搜索文件夹456 789中的文件夹456等特定字符串.

试过下面的代码.我在下面遗漏的东西: -

local function Loc_Lines( str )
--
local ret= {}   -- 0 lines

while str do
    local _,_,line,tail= string.find( str, "(.-)\n(.+)" )
    table.insert( ret, line or str )
    str= tail
  Print (str)
end

return ret
end


local function Loc_ShellCommand( cmd )
--
local str= nil

    --
    local f= io.popen( cmd )    -- no command still returns a handle :(
     if f then

        str= f:read'*a'
    Print(str)
        f:close()
    end

    if str=="" then   -- take no output as a failure (we can't tell..)
    Print("hi")
        str= nil
    end

-- Remove terminating linefeed, if any (eases up one-line analysis)
--
if str then
    if string.sub( str, -1 ) == '\n' then
        str= string.sub( str, 1, -2 )
    end
end

return str
 end


 local function Loc_DirCmd( cmd )

 Print(cmd)

  local str= Loc_ShellCommand( cmd )



 return Loc_Lines(str)
 end


local function Loc_DirList( dirname )

 local ret= {}

    local lookup= {}

   local tbl= Loc_DirCmd( "dir /AD /B "..dirname )   -- only dirs

    -- Add slash to every dir line
    --
    for i,v in ipairs(tbl) do
        table.insert( ret, v..'\\' )
        lookup[v]= true
    end       


    -- Return with forward slashes
    --
    if true then
        for i=1,table.getn(ret) do
            ret[i]= string.gsub( ret[i], '\\', '/' )
     Print (ret[i])
        end
    end


   return ret
 end


 Loc_DirList("C:\\Program Files\\")
Run Code Online (Sandbox Code Playgroud)

rho*_*ter 50

我讨厌必须安装库(特别是那些希望我使用安装程序包来安装它们的库).如果您正在为Lua中的绝对路径上的目录列表寻找一个干净的解决方案,请不要再看了.

基于sylvanaar提供的答案,我创建了一个函数,它返回给定目录的所有文件的数组(需要绝对路径).这是我首选的实现,因为它适用于我的所有机器.

-- Lua implementation of PHP scandir function
function scandir(directory)
    local i, t, popen = 0, {}, io.popen
    local pfile = popen('ls -a "'..directory..'"')
    for filename in pfile:lines() do
        i = i + 1
        t[i] = filename
    end
    pfile:close()
    return t
end
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Windows,则需要安装bash客户端以便'ls'命令可以工作 - 或者,您可以使用sylvanaar提供的dir命令:

'dir "'..directory..'" /b /ad'
Run Code Online (Sandbox Code Playgroud)

  • 不要解析`ls`. (8认同)
  • 当目录名称包含单引号(可能还有其他令人讨厌的字符)时,这会非常可怕.记住POSIX文件名只是字节字符串. (4认同)
  • 请注意:您的代码会为您提供所有文件; 给定的dir命令只为您提供目录.要获取所有文件,只需使用`dir <path>/b`(不要使用`/ ad`,它只指定目录.) (2认同)
  • 不要解析 `ls` 的输出。请改用“find -maxdepth 1 -print0”。“ls”的问题在于实现之间存在许多不一致,并且很少(如果有的话)允许使用文件名不能包含的分隔符(它们可以包含换行符!),最常见的是空字节,但斜杠可能也工作。 (2认同)

jpj*_*obs 25

采取简单的方法,安装lfs.然后使用以下构造来查找所需内容:

require'lfs'
for file in lfs.dir[[C:\Program Files]] do
    if lfs.attributes(file,"mode") == "file" then print("found file, "..file)
    elseif lfs.attributes(file,"mode")== "directory" then print("found dir, "..file," containing:")
        for l in lfs.dir("C:\\Program Files\\"..file) do
             print("",l)
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

注意反斜杠等于[[\]]等于"\\",如果没有在cmd本身上使用,那么在windows /中也是允许的(如果我错了,请纠正我).


syl*_*aar 16

 for dir in io.popen([[dir "C:\Program Files\" /b /ad]]):lines() do print(dir) end
Run Code Online (Sandbox Code Playgroud)

*适用于Windows

输出:

Adobe
Bitcasa
Bonjour
Business Objects
Common Files
DVD Maker
IIS
Internet Explorer
iPod
iTunes
Java
Microsoft Device Emulator
Microsoft Help Viewer
Microsoft IntelliPoint
Microsoft IntelliType Pro
Microsoft Office
Microsoft SDKs
Microsoft Security Client
Microsoft SQL Server
Microsoft SQL Server Compact Edition
Microsoft Sync Framework
Microsoft Synchronization Services
Microsoft Visual Studio 10.0
Microsoft Visual Studio 9.0
Microsoft.NET
MSBuild
...
Run Code Online (Sandbox Code Playgroud)

每次循环时,您都会获得一个新的文件夹名称.我选择以打印为例.

  • 注意:要获取文件列表,请仅使用“/b”而不是“/b /ad”。 (3认同)

Ger*_*ren 13

我不喜欢安装库,我正在使用内存功耗更低的嵌入式设备.我发现使用'ls'命令会导致内存不足.所以我创建了一个使用'find'来解决问题的函数.

这样就可以保持内存使用稳定并循环所有30k文件.

function dirLookup(dir)
   local p = io.popen('find "'..dir..'" -type f')  --Open directory look for files, save data in p. By giving '-type f' as parameter, it returns all files.     
   for file in p:lines() do                         --Loop through all files
       print(file)       
   end
end
Run Code Online (Sandbox Code Playgroud)

  • 此函数将递归遍历树,而不仅仅是列出目录. (2认同)
  • 要正确处理包含换行符的文件名,请使用“find ... -print0”并按空字节进行分割。您可能还想添加“-maxdepth 1”以避免递归到子目录。 (2认同)