Lua怎么一行一行读取文件?

文章导读
Previous Quiz Next 在 Lua 中,我们可以轻松地逐行读取文件。在本章中,我们将探索多种读取文件的方法。
📋 目录
  1. 示例 - 使用 io.read() 逐行读取文件
  2. 示例 - 使用 f:read() 逐行读取文件
  3. 示例 - 使用 io.lines() 逐行读取文件
A A

Lua - 逐行读取文件



Previous
Quiz
Next

在 Lua 中,我们可以轻松地逐行读取文件。在本章中,我们将探索多种读取文件的方法。

  • io.read([mode]) - 使用简单模式,我们可以使用 io.read() 方法逐行读取文件。每次调用 io.read() 方法都会返回从文件中读取的下一行。mode 是一个可选参数。我们可以指定 mode 为 "*line", 来逐行读取文件。

  • io.lines() - 使用简单模式,我们可以使用 io.lines() 方法逐行读取文件。io.lines() 返回一个迭代器,用于遍历文件的所有行。

  • file:read([mode]) - 使用完整模式,我们可以使用 file:read() 方法逐行读取文件,其中 file 表示由 io.open() 方法返回的文件句柄。每次调用 file.read() 方法都会返回从文件中读取的下一行。mode 是一个可选参数。我们可以指定 mode 为 "*line", 来逐行读取文件。

让我们探索上述每种逐行读取文件的方法。

我们将使用示例文件 example.txt,如下所示−

example.txt

Welcome to example.com
Simply Easy Learning

示例 - 使用 io.read() 逐行读取文件

现在让我们看看如何使用 io.read() 方法调用逐行读取文件。

main.lua

-- 读取文件内容并返回相同内容
function readFile()
   -- 以读取模式打开文件
   f = io.open("example.txt","r")
   -- 将 f 设置为默认输入
   io.input(f)
   -- 读取第一行
   print(io.read())
   -- 读取下一行
   print(io.read())
   -- 关闭文件句柄
   io.close(f)
   -- 返回内容
   return contents
end

-- 读取文件
readFile()

输出

当上述代码构建并执行时,会产生以下结果 −

Welcome to example.com
Simply Easy Learning

示例 - 使用 f:read() 逐行读取文件

现在让我们看看如何使用 f:read("*line") 方法调用逐行读取文件。

main.lua

-- 读取文件内容并返回相同内容
function readFile()
   -- 以读取模式打开文件
   f = io.open("example.txt","r")
   -- 读取第一行
   print(f:read(("*line")))
   -- 读取下一行   
   print(f:read("*line"))
   -- 关闭文件句柄
   f:close()
   -- 返回内容
   return contents
end

-- 读取文件
readFile()

输出

当上述代码构建并执行时,会产生以下结果 −

Welcome to example.com
Simply Easy Learning

示例 - 使用 io.lines() 逐行读取文件

现在让我们看看如何使用 io.lines() 方法调用逐行读取文件。

main.lua

-- 读取文件内容并返回相同内容
function readFile()
   -- 以读取模式打开文件
   f = io.open("example.txt","r")
   -- 将 f 设置为默认输入
   io.input(f)

   -- 遍历每一行
   for line in io.lines() do
      print(line)
   end

   -- 关闭文件句柄
   io.close(f)
   -- 返回内容
   return contents
end

-- 读取文件
readFile()

输出

当上述代码构建并执行时,会产生以下结果 −

Welcome to example.com
Simply Easy Learning