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
- Opening Files with io.open
- Reading File Contents
- Writing and Appending to Files
- Closing Files and Error Handling