Lua with Neowin: File I/O — io.open, Read Modes, Write Modes & io.lines | Episode 26
Video: Lua with Neowin: File I/O — io.open, Read Modes, Write Modes & io.lines | Episode 26 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lua File I/O: Using io.open, Read/Write Modes, and io.lines
Working with files is essential in many Lua programs. This guide covers how to open files using io.open with different modes for reading, writing, and appending, how to read file contents fully or line-by-line, write data back to files, and iterate over lines conveniently with io.lines. Always remember to close your file handles to avoid resource leaks.
Code
-- Open a file for reading ("r" mode)
local file, err = io.open("data.txt", "r")
if not file then
error("Could not open file: " .. err)
end
-- Read the entire file content as a single string
local content = file:read("*a")
print("Full file content:")
print(content)
file:close() -- Always close the file handle
-- Open a file for writing ("w" mode) - overwrites existing content
local fileWrite, errWrite = io.open("output.txt", "w")
if not fileWrite then
error("Could not open file for writing: " .. errWrite)
end
fileWrite:write("Hello, Lua file I/O!\n")
fileWrite:write("This line overwrites previous content.\n")
fileWrite:close()
-- Append to the file ("a" mode)
local fileAppend, errAppend = io.open("output.txt", "a")
if not fileAppend then
error("Could not open file for appending: " .. errAppend)
end
fileAppend:write("This line is appended.\n")
fileAppend:close()
-- Iterate over lines using io.lines (convenient shortcut)
print("Reading lines from output.txt:")
for line in io.lines("output.txt") do
print(line)
end
Key Points
io.open(path, mode)opens a file and returns a file handle or an error message.- Use mode
"r"for reading,"w"to write (overwriting), and"a"to append. file:read("*a")reads the entire file at once, whilefile:read("*l")reads one line at a time.file:write(text)writes strings to the file; opening in"w"mode overwrites,"a"appends.io.lines(path)provides a simple iterator to loop through each line of a file without manually opening or closing it.- Always call
file:close()to free system resources after file operations.