0Pricing
Lua Academy · 课时

使用 io.open 打开文件

使用 io.open 以读取、写入和追加模式打开文件。

使用 io.open 打开文件 是 CoddyKit 上的免费 Lua Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Lua Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Lua Academy 课程共包含 4 节课。

io.open 语法

io.open(filename, mode) 打开文件并返回文件句柄;如果失败,则返回 nil 和错误消息。模式字符串:"r" 读取(默认);"w" 写入(截断);"a" 追加;"r+" 读写;"b" 二进制后缀。

local f, err = io.open("test.txt", "w")
if not f then
  print("Error:", err)
  return
end
f:write("Hello, Lua!\n")
f:close()
print("Written successfully")

读取模式

使用 "r" 模式打开现有文件以进行读取。请始终检查 nil:如果文件不存在,io.open 会返回 nil 和错误消息。不要假定文件一定存在。

local f, err = io.open("test.txt", "r")
if not f then
  print("Cannot open:", err)
  return
end
local content = f:read("*a")  -- read all
f:close()
print(content)

写入和追加模式

"w" 会创建文件或截断现有文件。"a" 会在需要时创建文件,并始终追加到文件末尾。如果您不希望丢失之前的内容,请对日志文件使用追加模式。

-- Write (creates/truncates)
local f = io.open("log.txt", "w")
f:write("Session started\n")
f:close()

-- Append (adds to end)
local g = io.open("log.txt", "a")
g:write("Event: login\n")
g:write("Event: action\n")
g:close()

二进制模式

在任意模式后添加 "b",即可进行二进制读写。在 Unix 上,文本模式和二进制模式相同。在 Windows 上,文本模式会将 \n 转换为 \r\n;二进制模式则会禁用此转换。对于非文本文件,请始终使用二进制模式。

-- Binary read
local f = io.open("image.png", "rb")
if f then
  local header = f:read(8)   -- read 8 bytes
  f:close()
  -- Check PNG magic number: \137PNG\r\n\26\n
  print("Read", #header, "bytes")
end

-- Binary write
local g = io.open("out.bin", "wb")
if g then
  g:write(string.char(0x89, 0x50, 0x4E, 0x47))
  g:close()
end

文件句柄方法

文件句柄(由 io.open 返回)具有以下方法:f:read(...)、f:write(...)、f:lines()、f:seek(whence, offset)、f:flush()、f:close()。请使用冒号语法在句柄上调用这些方法。

local f = io.open("data.txt", "w")
f:write("line 1\n")
f:write("line 2\n")
f:write("line 3\n")
f:flush()   -- force write to disk
f:close()

local g = io.open("data.txt", "r")
for line in g:lines() do
  print(line)
end
g:close()

io.input 和 io.output

io.input(f) 设置默认输入文件;io.output(f) 设置默认输出。io.read() 从当前输入中读取数据;io.write() 将数据写入当前输出。默认输入是标准输入,默认输出是标准输出。

-- Read from stdin (default input)
local line = io.read()  -- reads one line
print("You entered:", line)

-- Set default output to a file
io.output("out.txt")
io.write("This goes to out.txt\n")
io.output(io.stdout)  -- restore stdout

检查文件是否存在

Lua 没有 file.exists(),但您可以使用读取模式下的 io.open——如果操作失败,说明文件不存在(或无法访问)。此外,在 POSIX 系统上可以使用 os.execute 或 lfs 库。

local function fileExists(path)
  local f = io.open(path, "r")
  if f then f:close(); return true end
  return false
end

print(fileExists("test.txt"))     -- true/false
print(fileExists("noexist.txt"))  -- false

使用模式读取

f:read() 接受格式字符串:"l" 或 "*l" 读取一行(去除换行符);"L" 保留换行符;"n" 读取一个数字;"a" 或 "*a" 读取到 EOF;传入数字则读取相应数量的字节。

local f = io.open("data.txt", "r")
if f then
  local line1 = f:read("l")   -- first line, no newline
  local num   = f:read("n")   -- next number in file
  local rest  = f:read("a")   -- rest of file
  f:close()
  print(type(line1), type(num))
end

临时文件

io.tmpfile() 以读写模式打开一个临时文件。程序退出或文件句柄被垃圾回收时,该文件会自动删除。您可以使用它进行中间处理,而无需管理文件名。

local tmp = io.tmpfile()
tmp:write("temporary data\n")
tmp:write("more data\n")

-- Seek back to start and read
tmp:seek("set", 0)
local content = tmp:read("a")
print(content)
-- File auto-deleted when tmp is collected

使用 lines() 迭代行

f:lines() 返回一个迭代器,每次读取一行。迭代器耗尽后会自动关闭文件。对于大型文件,这种方式非常节省内存,因为它不会一次性加载整个文件。

local function countLines(path)
  local count = 0
  local f, err = io.open(path, "r")
  if not f then return nil, err end
  for _ in f:lines() do
    count = count + 1
  end
  -- f is closed automatically by lines()
  return count
end

local n, err = countLines("data.txt")
print("Lines:", n)

快速检查

如果文件不存在,io.open("file.txt", "a") 会执行什么操作?

回顾:io.open

总结:

  • io.open(path, mode) 返回句柄,或返回 nil 和错误信息
  • 模式:r w a r+ b
  • 使用句柄前始终检查它是否为 nil
  • 完成后调用 f:close()
  • 使用 f:lines() 以节省内存地迭代文件行
  • 使用 io.tmpfile() 创建自动删除的临时文件

常见问题解答

「使用 io.open 打开文件」课时是免费的吗?

是的 — 「使用 io.open 打开文件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Lua Academy 课程的其余内容,请升级到 CoddyKit PRO。 Lua Academy 课程共包含 4 节课。

「使用 io.open 打开文件」这节课中我会学到什么?

使用 io.open 以读取、写入和追加模式打开文件。 你通过在浏览器中直接运行的动手代码来练习 Lua Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Lua Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Lua Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用 io.open 打开文件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Lua Academy 课中编写并运行代码吗?

能。每节 Lua Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 io.open 打开文件
  2. 读取文件内容
  3. 写入和追加文件内容
  4. 关闭文件和错误处理
← 返回 Lua Academy