Lua 文件 I/O
文件 I/O 用于读取和写入文件。你可以用它保存配置、读取日志、处理传感器数据文件,或者生成结果报告。
Lua 提供两种常见文件操作方式:
- 简单函数,例如
io.input()、io.read()、io.write()。 - 文件句柄,例如
io.open()返回的 file object。
实际项目中更推荐使用文件句柄,因为它更明确,也更容易处理错误。
写入文件
下面创建文件 hello.txt 并写入一行文本:
write-file.lua
local file = assert(io.open("hello.txt", "w"))
file:write("Hello, Lua!\n")
file:close()
运行:
lua write-file.lua
当前目录会生成 hello.txt。
io.open("hello.txt", "w") 表示以写入模式打开文件。如果文件不存在,会创建文件;如果文件已存在,会覆盖原内容。
读取整个文件
read-file.lua
local file = assert(io.open("hello.txt", "r"))
local content = file:read("*a")
file:close()
print(content)
输出:
Hello, Lua!
"*a" 表示读取整个文件。
按行读取文件
如果文件可能很大,按行读取更合适:
read-lines.lua
local file = assert(io.open("hello.txt", "r"))
for line in file:lines() do
print(line)
end
file:close()
也可以直接使用 io.lines():
for line in io.lines("hello.txt") do
print(line)
end
io.lines(filename) 会在迭代结束后自动关闭文件。使用显式文件句柄时,你要自己调用 close()。