国际访客建议访问 Primers 编程伙伴 国际版站点 > Lua 教程 > io-module 以获得更好的体验。

# Lua 的 IO 模块

请查看 Lua 标准库模块列表 了解更多相关 API。
函数 说明
io.stderr 标准错误流
io.stdin 标准输入流
io.stdout 标准输出流
函数 说明
io.close 关闭 IO 流
io.flush 冲洗 IO 流
io.input 设置默认输入流
io.lines 逐行迭代 IO 流
io.open 打开文件
io.output 设置默认输出流
io.popen 运行一个程序并绑定管道
io.read 读取默认输入流
io.tmpfile 打开临时文件
io.type 检查 IO 流是否有效
io.write 写默认输出流
file:close 关闭 IO 流
file:flush 冲洗 IO 流
file:lines 逐行迭代 IO 流
file:read 读取 IO 流
file:seek 设置 IO 流的位置指示器
file:setvbuf 设置 IO 流的缓冲模式
file:write 写 IO 流

# io.close

io.close ([file])

!subtitle:说明

关闭 IO 流,等价于 file:close。如果不带 file 参数,则关闭默认输出流(io.output),等价于 io.output():close()

!subtitle:参数

  • file - 要关闭的 IO 流;默认为 io.output

!subtitle:返回值

!subtitle:示例

运行示例

-- 写文件
local fp = io.open('/tmp/1.txt', 'w')   -- 打开文件
fp:write("Hello\n")                     -- 写文件
io.close(fp)                            -- 关闭文件

-- 读文件
fp = io.open('/tmp/1.txt', 'r')     -- 打开文件
print(fp:read())                    -- 读文件
io.close(fp)                        -- 关闭文件

# io.flush

io.flush ()

!subtitle:说明

冲洗默认输出流(io.output),等价于 io.output():flush()

!subtitle:参数

!subtitle:返回值

!subtitle:示例

运行示例

io.write("hello world")     -- 写默认输出流
io.flush()                  -- 冲洗默认输出流

# io.input

io.input ([filename])

!subtitle:说明

以文本模式打开文件 filename,并将其设为默认输入流,返回该输入流。

如果不带参数,则返回当前的默认输入流。

初始的默认输入流是 io.stdin

!subtitle:参数

  • filename - 要设为默认输入流的文件路径

!subtitle:返回值

  • 返回新的默认输入流

!subtitle:示例

运行示例

-- 查看默认输入流
print(io.input())

-- 设置默认输入流
local fp = io.open('/tmp/1.txt', 'w')       -- 创建文件
fp:close()
print(io.input('/tmp/1.txt'))               -- 设置

# io.lines

io.lines ([filename, ···])

以读模式打开指定的文件 filename,并返回一个迭代器函数,该迭代器函数每次调用时按照指定格式读取一次文件并返回。

迭代到文件结束时,迭代器返回 nil 并自动关闭文件。

不带参数时迭代默认输入流(io.input())。

!subtitle:参数

  • filename - 要迭代的文件路径

  • ... - 迭代的读取格式,参考 io.read;默认为 "l",即读取一行

!subtitle:返回值

  • 返回迭代器函数

!subtitle:示例

运行示例

-- 写文件
local fp = io.open('/tmp/1.txt', 'w')
fp:write("AAA\n")
fp:write("BBB\n")
fp:write("CCC\n")
fp:write("DDD\n")
fp:write("EEE\n")
fp:close()

-- 迭代
for v in io.lines('/tmp/1.txt') do
    print(v)
end

# io.open

!subtitle:说明

io.open (filename [, mode])

mode 模式打开文件 filename,返回打开的文件流。

模式说明符 意义 说明 操作权限 如果文件存在 如果文件不存在
"r" 读模式 打开文件进行读取 从文件开头进行操作 打开失败
"w" 写模式 创建用于写入的文件 清空原文件 新建文件
"a" 追加模式 追加写入文件 从文件末尾进行操作 新建文件
补充说明符 意义 说明 操作权限 示例
"+" 更新模式 文件既可读也可写 可读可写 "r+" "w+" "a+"
"b" 二进制模式 以二进制模式打开文件 "rb" "wb" "ab" "w+b"
  • 文本模式下(即不含 "b"),读写文件时会跳过不可打印字符,参考 isprint。但在类 POSIX 系统上无效,类 POSIX 系统始终以二进制模式打开

  • 追加模式("a")下,无论文件位置指示器的当前位置如何,进行写操作时都会向文件末尾写入。

!subtitle:参数

  • filename - 要打开的文件路径

  • mode - 文件的打开模式

!subtitle:返回值

  • 成功时返回打开的文件流

  • 失败时返回 nil

!subtitle:示例

运行示例

-- 写文件
local fp = io.open('/tmp/1.txt', 'w')   -- 打开文件
fp:write("Hello\n")                     -- 写文件
fp:close()                              -- 关闭文件

-- 读文件
fp = io.open('/tmp/1.txt', 'r')     -- 打开文件
print(fp:read())                    -- 读文件
fp:close()                          -- 关闭文件

# io.output

io.output ([filename])

以文本模式打开文件 filename,并将其设为默认输出流,返回该输出流。

如果不带参数,则返回当前的默认输出流。

初始的默认输出流是 io.stdout

!subtitle:参数

  • filename - 要设为默认输出流的文件路径

!subtitle:返回值

  • 返回新的默认输出流

!subtitle:示例

运行示例

-- 查看默认输出流
print(io.output())

-- 设置默认输出流
local fp = io.open('/tmp/1.txt', 'w')       -- 创建文件
fp:close()
print(io.output('/tmp/1.txt'))              -- 设置

# io.popen

io.popen (prog [, mode])

!subtitle:说明

在单独的进程中启动程序 prog,并返回一个 IO 流:

  • 读取该 IO 流时相当于读取 prog 的标准输出

  • 写入该 IO 流时相当于写入 prog 的标准输入

仅支持以 "r""w" 模式打开,即只读或只写。

此功能依赖于系统,并且并非在所有平台上都可用。

!subtitle:参数

  • prog - 要运行的程序

  • mode - IO 流的打开模式,仅支持 "r""w" 模式

!subtitle:返回值

  • 成功时返回 IO liu

  • 失败时返回 nil

!subtitle:示例

-- 向 grep 输入数据并过滤包含 "error" 的行
local fp = io.popen("grep -i error", "w")
if fp then
    local logs = {
        "INFO: System started",
        "ERROR: Database connection failed",
        "WARNING: High memory usage",
        "ERROR: File not found",
        "DEBUG: Processing complete"
    }
    
    for _, log in ipairs(logs) do
        fp:write(log .. "\n")       -- 写数据
    end
    fp:close()                      -- 关闭流
end

运行结果

ERROR: Database connection failed
ERROR: File not found

# io.read

io.read (···)

!subtitle:说明

读取默认输入流(io.input()),相当于 io.input():read(···)

格式 说明
"n" 读取一个数值
"a" 读取剩余的全部文本
"l" 读取一行,丢弃换行符(默认)
"L" 读取一行,保留换行符
整数 读取相应字节的字符串

!subtitle:参数

  • ... - 读取格式,每个格式对应一个返回值

    • "n" - 读取一个数值

    • "a" - 读取剩余的全部文本

    • "l" - 读取一行,丢弃换行符(默认)

    • "L" - 读取一行,保留换行符

    • 整数 - 读取相应字节的字符串

!subtitle:返回值

  • 成功时格式对应位置返回读取到的值

  • 失败时格式对应位置返回 nil

!subtitle:示例

运行示例

-- 写文件
local pi = io.read("n")
print(type(pi), pi)

# io.tmpfile

io.tmpfile ()

!subtitle:说明

"w+" 模式打开一个临时文件,返回该文件流。

程序退出时临时文件会自动删除。

!subtitle:参数

!subtitle:返回值

  • 成功时返回文件流

  • 失败时返回 nil

!subtitle:示例

运行示例

-- 写文件
local fp = io.tmpfile() -- 打开临时文件
fp:write("Hello\n")     -- 写
fp:write("World\n")

fp:seek("set")
print(fp:read("a"))
fp:close()

# io.type

io.type (obj)

!subtitle:说明

检查参数 obj 是否是有效的 IO 流。

!subtitle:参数

  • obj - 要检查的对象

!subtitle:返回值

  • 如果 obj 是有效的 IO 流则返回字符串 "file"

  • 如果 obj 是关闭的 IO 流则返回字符串 "closed file"

  • 如果 obj 不是 IO 流则返回 nil

!subtitle:示例

运行示例

print(io.type(10))

local fp = io.tmpfile()
print(io.type(fp))

fp:close()
print(io.type(fp))

# io.write

io.write (···)

!subtitle:说明

写入默认输出流(io.output()),相当于 io.output():write(···)

!subtitle:参数

  • ... - 要写的参数列表

!subtitle:返回值

  • 返回默认输出流 io.output()

# file:close

file:close ()

!subtitle:说明

关闭 IO 流 file

IO 流可以被垃圾收集器自动关闭,因此手动调用这个函数并不是必须的。

但是垃圾收集的实际不可预测,因此手动关闭更加及时。

!subtitle:参数

!subtitle:返回值

  • 是(true)否(false)成功

!subtitle:示例

local fp = io.open('/tmp/1.txt', 'w')   -- 打开文件
fp:close()

# file:flush

file:flush ()

!subtitle:说明

冲洗 IO 流,将缓冲区中的数据实际写入文件。

文件关闭时会自动冲洗。

!subtitle:参数

!subtitle:返回值

  • 是(true)否(false)成功

!subtitle:示例

运行示例

-- 写文件
local fp = io.open('/tmp/1.txt', 'w')   -- 打开文件
fp:write("Hello\n")                     -- 写
fp:write("2025\n")
fp:write("World\n")
fp:write("Creeper\n")
fp:write("Oh Man\n")

-- 读文件
local fp2 = io.open('/tmp/1.txt', 'r')   -- 打开文件
print('冲洗前', fp2:read("a"))           -- 读
fp2:close()                              -- 关闭

-- 冲洗
fp:flush()

-- 读文件
fp2 = io.open('/tmp/1.txt', 'r')         -- 打开文件
print('冲洗后', fp2:read("a"))           -- 读
fp2:close()                              -- 关闭

# file:lines

file:lines (···)

!subtitle:说明

返回一个迭代器函数,该迭代器函数每次调用时按照指定格式读取 IO 流 file 并返回。

迭代到文件结束时,迭代器返回 nil 并自动关闭文件。

!subtitle:参数

  • ... - 迭代的读取格式,参考 file.read;默认为 "l",即读取一行

!subtitle:返回值

  • 返回迭代器函数

!subtitle:示例

运行示例

-- 写文件
local fp = io.open('/tmp/1.txt', 'w+')
fp:write("AAA\n")
fp:write("BBB\n")
fp:write("CCC\n")
fp:write("DDD\n")
fp:write("EEE\n")
fp:seek("set")

-- 迭代
for v in fp:lines() do
    print(v)
end

# file:read

file:read (···)

!subtitle:说明

读取文件内容。

格式 说明
"n" 读取一个数值
"a" 读取剩余的全部文本
"l" 读取一行,丢弃换行符(默认)
"L" 读取一行,保留换行符
整数 读取相应字节的字符串

!subtitle:参数

  • ... - 读取格式,每个格式对应一个返回值

    • "n" - 读取一个数值

    • "a" - 读取剩余的全部文本

    • "l" - 读取一行,丢弃换行符(默认)

    • "L" - 读取一行,保留换行符

    • 整数 - 读取相应字节的字符串

!subtitle:返回值

  • 成功时格式对应位置返回读取到的值

  • 失败时格式对应位置返回 nil

!subtitle:示例

运行示例

-- 写文件
local fp = io.open('/tmp/1.txt', 'w')   -- 打开文件
fp:write("Hello\n")                     -- 写文件
fp:write("2025\n")
fp:write("World\n")
fp:write("Creeper\n")
fp:write("Oh Man\n")
fp:close()

-- 读文件
fp = io.open('/tmp/1.txt', 'r')         -- 打开文件
io.write("'", fp:read(), "'\n")                        -- 默认 "l",读取一行,丢弃换行符
io.write("'", fp:read("n"), "'\n")                     -- 读取一个数值
io.write("'", fp:read("l"), "'\n")                     -- 读取一行,丢弃换行符(读取并丢弃 2025 后面的换行)
io.write("'", fp:read("L"), "'\n")                     -- 读取一行,保留换行符
io.write("'", fp:read("a"), "'\n")                     -- 读取全部剩余文件

# file:seek

file:seek ([whence [, offset]])

!subtitle:说明

设置文件当前位置,返回设置后的位置。

不带参数时当前位置不变,直接返回当前位置。

原点 说明
"set" 相对于文件开头
"cur" 相对于当前位置
"end" 相对于文件末尾

!subtitle:参数

  • whence - 相对原点

    • "set" - 相对于文件开头

    • "cur" - 相对于当前位置(默认值)

    • "end" - 相对于文件末尾

  • offset - 相对于原点 whence 的偏移量,默认为 0

!subtitle:返回值

  • 设置后的当前位置

!subtitle:示例

运行示例

local fp = io.open('/tmp/1.txt', 'w+')
print('当前位置', fp:seek())        -- 读取当前位置
fp:write("AAA\n")
fp:write("BBB\n")
fp:write("CCC\n")
fp:write("DDD\n")
fp:write("EEE\n")
print('当前位置', fp:seek())        -- 读取当前位置

print('设置当前位置', fp:seek("set"))   -- 重设到文件开头
print(fp:read("a"))     -- 读取整个文件

# file:setvbuf

file:setvbuf (mode [, size])

!subtitle:说明

设置 IO 流的缓冲模式和缓冲区大小。

名称 说明
"full" 全缓冲 缓冲区满时写入目标设备
"line" 行缓冲 缓冲区满或遇到换行符(\n)时写入目标设备
"no" 无缓冲 数据直接写入目标设备

每种模式的特定行为都是不可移植的;请检查平台中底层的 ISO C 函数以获取更多详细信息;参考 setvbuf

通常情况下:

  • 标准输出(stdout)默认使用行缓冲

  • 标准输入(stdin)默认使用行缓冲

  • 标准错误(stderr)默认使用无缓冲

  • 文件默认使用全缓冲

!subtitle:参数

  • mode - 缓冲模式

    • "full" - 全缓冲

    • "line"- 行缓冲

    • "no" - 无缓冲

  • size - 缓冲区大小

!subtitle:返回值

  • 是(true)否(false)成功

运行示例

-- 写文件
local w1 = io.open('/tmp/1.txt', 'w')   -- 打开文件
w1:write("Hello World\n")               -- 写

-- 读文件
local r1 = io.open('/tmp/1.txt', 'r')   -- 打开文件
print('默认(全缓冲)', r1:read("a"))   -- 读
r1:close()                              -- 关闭

-- 写文件
local w2 = io.open('/tmp/2.txt', 'w')   -- 打开文件
w2:setvbuf("no")                        -- 设为无缓冲
w2:write("Hello World\n")               -- 写

-- 读文件
local r2 = io.open('/tmp/2.txt', 'r')   -- 打开文件
print('无缓冲', r2:read("a"))   -- 读
r2:close()                              -- 关闭

# file:write

file:write (···)

!subtitle:说明

写入 IO 流 file

!subtitle:参数

  • ... - 要写的参数列表

!subtitle:返回值

  • 返回 file

!subtitle:示例

运行示例

-- 写文件
local fp = io.open('/tmp/1.txt', 'w')
fp:write("AAA\n")
fp:write("BBB\n")
fp:write("CCC\n")
fp:write("DDD\n")
fp:write("EEE\n")
fp:close()

-- 读文件
local fp2 = io.open('/tmp/1.txt', 'r')
print(fp2:read("a"))

# 推荐阅读

Input and Output Facilities - Lua 5.4 Reference Manual

本文 更新于: 2025-11-27 09:38:13 创建于: 2025-11-27 09:38:13