蓝色天空网mbsky.com · 知识 · 实践 · 创造Lua · 本地阅读预览
教程 / 编程语言 / Lua

Lua 文件 I/O

详解 Lua I/O 库的简单模式(默认输入输出句柄)与完全模式(面向对象文件句柄)、io.open 打开模式、read 格式参数、file:seek 定位及 io.lines / io.tmpfile 等辅助方法。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

I/O 双模式与 io.open 打开模式

Lua `io` 标准库提供“简单模式”和“完全模式”两套接口。简单模式(simple model)维护全局唯一的默认输入文件与默认输出文件,写法贴近 C 语言标准 I/O,适合单一文件读写;完全模式(complete model)则以面向对象方式在外部文件句柄上通过冒号语法调用方法(如 `file:read()`),非常适合同时操作多个文件。使用 `file = io.open(filename [, mode])` 打开文件(失败时返回 `nil` 与错误信息),常用打开模式见表 1。

简单模式读写、read 参数与辅助函数

在简单模式中,先以 `"r"` 打开 `test.lua` 并通过 `io.input(file)` 设为默认输入,随后调用 `io.read()` 读取首行并 `io.close(file)` 关闭;接着以 `"a"` 追加模式打开并通过 `io.output(file)` 设为默认输出,调用 `io.write(...)` 在末尾追加注释而不破坏原有内容。`io.read()` 不带参数时默认按行读取(`"*l"`,Lua 5.3+ 亦支持省略星号写作 `"l"`/`"a"`/`"n"`),完整读取格式见表 2。

`io` 模块还提供多项实用工具:`io.tmpfile()` 返回以更新模式打开、程序结束自动删除的临时文件句柄;`io.type(obj)` 检测句柄状态(打开句柄返回 `"file"`、已关闭句柄返回 `"closed file"`、非句柄返回 `nil`);`io.flush()` 将默认输出缓冲区数据立即刷入磁盘;`io.lines([filename])` 返回逐行迭代器,读至文件尾返回 `nil`。

完全模式、file:seek 随机定位与 io.lines 行为差异

完全模式直接通过文件句柄调用 `file:read()`、`file:write()`、`file:flush()` 与 `file:close()`,参数规则与简单模式一致,可同时持有并交替读写多个文件。随机定位使用 `file:seek([whence [, offset]])`,其中 `whence` 可取 `"set"`(文件头)、`"cur"`(当前位置,默认)或 `"end"`(文件尾),`offset` 默认 `0`;成功时返回按字节计的新位置(如 `file:seek("end")` 可直接获取文件总字节数,`file:seek("end", -25)` 配合 `file:read("*a")` 可从倒数第 25 字节读至文件尾)。此外需留意 `io.lines` 的自动关闭差异:传入文件名 `io.lines("main.lua")` 在迭代到 EOF 时会自动关闭文件,而不带参数 `io.lines()` 等价于 `io.input():lines()`,结束时不会关闭默认输入句柄。

io.open 文件打开模式对照表

模式打开方式与文件存在性行为
r只读模式打开(默认),目标文件必须已存在。
w只写模式打开:文件已存在则清空原内容(长度归零),不存在则新建。
a追加只写模式:保留原内容并在文件尾写入,文件不存在则新建。
r+读写更新模式打开,目标文件必须已存在。
w+读写模式打开:文件存在则清空内容,不存在则新建。
a+读写追加模式:允许读取,写入内容始终追加到文件末尾。
b二进制模式标志(如 "rb"、"wb"),在 Windows 上避免换行符转换。
+更新修饰符,附加在 r/w/a 后表示同时允许读和写。

io.read / file:read 读取格式参数表

格式参数读取语义与 EOF 行为(Lua 5.3+ 可省略前缀 *)
"*n" / "n"读取并返回一个数字,若当前位置无法解析为数字则返回 nil。
"*a" / "a"从当前文件偏移起读取剩余全部内容(已在 EOF 时返回空字符串 "")。
"*l" / "l"(默认)读取下一行并去掉末尾换行符(保留换行可用 "L"),到 EOF 返回 nil。
number(正整数 n)读取至多 n 个字节的字符串,遇到 EOF 返回 nil(传 0 用于测试是否到达 EOF)。

在临时目录离线校验文件打开模式、read 四种格式、seek 逆向定位及 tmpfile/io.lines

python · 阅读源码
"""Offline Lua 5.4 semantic verification lab for Chapter 18 (file-io)."""
import json
import re
import tempfile
from pathlib import Path

VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"


def case_open_modes_and_simple_io_workflow():
    with tempfile.TemporaryDirectory() as tmp:
        target = Path(tmp) / "test.lua"
        target.write_text("-- test.lua 文件\nprint('ok')\n", encoding="utf-8")

        # Simple mode: open r -> read first line -> close
        with target.open("r", encoding="utf-8") as fh:
            first_line = fh.readline().rstrip("\r\n")

        # Simple mode: open a -> append comment -> close
        with target.open("a", encoding="utf-8") as fh:
            fh.write("-- test.lua 文件末尾注释")

        lines = target.read_text(encoding="utf-8").splitlines()
    expected = {
        "first_line": "-- test.lua 文件",
        "line_count_after_append": 3,
        "last_line": "-- test.lua 文件末尾注释",
    }
    actual = {
        "first_line": first_line,
        "line_count_after_append": len(lines),
        "last_line": lines[-1],
    }
    return {
        "name": "open_modes_and_simple_io_workflow",
        "summary": "在临时目录模拟简单模式 r 读取首行与 a 追加末尾注释,确认原有内容保留",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_read_formats_n_a_l_and_count():
    with tempfile.TemporaryDirectory() as tmp:
        p = Path(tmp) / "data.txt"
        p.write_text("42.5 hello\nsecond line\n12345rest", encoding="utf-8")
        raw = p.read_text(encoding="utf-8")

        # "*n" reads numeric prefix
        m_num = re.match(r"\s*([+-]?\d+(?:\.\d+)?)", raw)
        read_n = float(m_num.group(1)) if m_num else None
        rem = raw[m_num.end() :] if m_num else raw

        # "*l" reads rest of current line without newline
        first_nl = rem.find("\n")
        read_l1 = rem[:first_nl]
        rem2 = rem[first_nl + 1 :]
        second_nl = rem2.find("\n")
        read_l2 = rem2[:second_nl]
        rem3 = rem2[second_nl + 1 :]

        # number (5) reads 5 characters; "*a" reads remaining content
        read_5 = rem3[:5]
        read_a = rem3[5:]

    expected = {
        "read_n": 42.5,
        "read_l1": " hello",
        "read_l2": "second line",
        "read_5": "12345",
        "read_a": "rest",
    }
    actual = {
        "read_n": read_n,
        "read_l1": read_l1,
        "read_l2": read_l2,
        "read_5": read_5,
        "read_a": read_a,
    }
    return {
        "name": "read_formats_n_a_l_and_count",
        "summary": "校验 io.read / file:read 的 *n、*l、指定字节数与 *a 四种读取格式",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_complete_mode_seek_and_flush():
    with tempfile.TemporaryDirectory() as tmp:
        p = Path(tmp) / "seek_test.lua"
        payload = b"-- test.lua header\n-- tail_marker--test"
        p.write_bytes(payload)

        with p.open("rb") as fh:
            fh.seek(0, 2)  # file:seek("end", 0) -> file size
            total_size = fh.tell()
            fh.seek(-19, 2)  # file:seek("end", -19)
            tail = fh.read().decode("utf-8")
            fh.seek(0, 0)  # file:seek("set", 0)
            pos_start = fh.tell()

    expected = {
        "total_size": len(payload),
        "tail_slice": "-- tail_marker--test"[1:],
        "pos_after_set": 0,
    }
    actual = {"total_size": total_size, "tail_slice": tail, "pos_after_set": pos_start}
    return {
        "name": "complete_mode_seek_and_flush",
        "summary": "校验完全模式下 file:seek(\"end\", -offset) 逆向定位读取尾部及 set/cur/end 基准",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_tmpfile_io_type_and_lines_iterator():
    with tempfile.TemporaryDirectory() as tmp:
        p = Path(tmp) / "main.lua"
        p.write_text("line1\nline2\nline3\n", encoding="utf-8")
        iterated = [ln.rstrip("\r\n") for ln in p.open("r", encoding="utf-8")]

    tf = tempfile.TemporaryFile(mode="w+", encoding="utf-8")
    open_type = "file" if not tf.closed else "closed file"
    tf.write("temp-data")
    tf.flush()
    tf.seek(0)
    temp_val = tf.read()
    tf.close()
    closed_type = "closed file" if tf.closed else "file"
    non_file_type = None

    expected = {
        "lines_iterated": ["line1", "line2", "line3"],
        "temp_val": "temp-data",
        "io_type_states": ["file", "closed file", None],
    }
    actual = {
        "lines_iterated": iterated,
        "temp_val": temp_val,
        "io_type_states": [open_type, closed_type, non_file_type],
    }
    return {
        "name": "tmpfile_io_type_and_lines_iterator",
        "summary": "校验 io.tmpfile 自动清理临时句柄、io.type 三态(file/closed file/nil)及 io.lines 逐行迭代",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_open_modes_and_simple_io_workflow(),
        case_read_formats_n_a_l_and_count(),
        case_complete_mode_seek_and_flush(),
        case_tmpfile_io_type_and_lines_iterator(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线脚本全程在 tempfile.TemporaryDirectory 中安全执行,确认 r/a 简单模式、*n/*l/字节数/*a 读取、file:seek("end", -offset) 尾部读取以及 tmpfile 与 io.type 三态。
在临时目录离线校验文件打开模式、read 四种格式、seek 逆向定位及 tmpfile/io.lines

所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。

当前源码 SHA256:87fa70c875bcae16b0195560237f556b2c4b13fb36f8486487d29fbf8749a386

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Lua 文件 I/O实验

所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。

ZIP SHA256:7d89c7c61e1b0ec7ffb17b21eac7b6b98c87706de294f0a71a4fa43d1baff785

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在读取包含图片或压缩包等二进制数据的文件时,为什么在 Windows 环境下必须给 `io.open` 加上 `b` 模式(如 `"rb"`)?

展开参考解答

Windows 文本模式下 C 标准库会把 `\r\n` 转换并在遇到字节 `0x1A`(Ctrl+Z)时提前判定为文件结束;加上 `b` 二进制模式可确保字节原样无损读写。

规范与官方依据