0Pricing
Lua Academy · Lesson

Opening Files with io.open

Open files in read, write, and append modes using io.open.

io.open Syntax

io.open(filename, mode) opens a file and returns a file handle, or nil plus an error message on failure. Mode strings: "r" read (default), "w" write (truncate), "a" append, "r+" read/write, "b" suffix for binary.

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")

Read Mode

Open in "r" mode to read an existing file. Always check for nil — if the file doesn't exist, io.open returns nil and an error message. Never assume the file is there.

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)

All lessons in this course

  1. Opening Files with io.open
  2. Reading File Contents
  3. Writing and Appending to Files
  4. Closing Files and Error Handling
← Back to Lua Academy