如何在 Lua 中读取一个目录中的一堆文件

我有一个指向目录的路径(作为一个字符串)。在那个目录里,有很多文本文件。我想进入那个目录,打开它,并且去读取每个文本文件里的数据。

我尝试了:

f = io.open(path)
f:read("*a")

我得到了错误信息“nil是一个目录”

我也尝试了:

f = io.popen(path)

我得到了错误信息:“权限被拒绝”

难道只有我这样认为吗?用Lua做基本的文件IO好像比应该的要难很多?

点赞
用户258523
用户258523

将下面翻译成中文并且保留原本的 markdown 格式

A directory isn't a file. You can't just open it.

一个目录不是一个文件,你不能直接打开它。

And yes, lua itself has (intentionally) limited functionality.

You can use [luafilesystem](https://keplerproject.github.io/luafilesystem/) or [luaposix](https://github.com/luaposix/luaposix) and similar modules to get more features in this area.

Lua本身有(故意)限制的功能。

你可以使用[luafilesystem](https://keplerproject.github.io/luafilesystem/)或[luaposix](https://github.com/luaposix/luaposix)和类似的模块来获得更多在这个领域的功能。

2015-06-10 16:52:56
用户343123
用户343123

你也可以使用以下脚本列出指定目录中文件的名称(假设是Unix/Posix):

dirname = '.'
f = io.popen('ls ' .. dirname)
for name in f:lines() do print(name) end
2015-06-10 17:09:05