Skip to content
Lua

File I/O

Read and write files in Lua.

By EZ4Code Team
iofile

Code

-- Write (default 'w')
local f = io.open("output.txt", "w")
f:write("Line 1\n")
f:write("Line 2\n")
f:close()

-- Append
local f2 = io.open("log.txt", "a")
f2:write(os.date() .. " - event\n")
f2:close()

-- Read all
local f3 = io.open("data.txt", "r")
local content = f3:read("*a")  -- "*a" = all, "*l" = line, "*n" = number
f3:close()
print(content)

-- Read line by line
for line in io.lines("data.txt") do
  print(line)
end

-- Standard streams
io.write("Enter name: ")
local name = io.read("*l")  -- or "*L" to keep newline
print("Hello, " .. name)

-- Binary
local f4 = io.open("data.bin", "rb")
local data = f4:read("*a")
f4:close()

Explanation

io.open returns a file handle or nil + error message on failure — always check. Modes: r/w/a/b (binary). read('*a') reads everything; read('*l') reads one line (without newline); read('*n') reads a number. io.lines returns an iterator for line-by-line reading. Always close handles to flush buffers and avoid leaks.

More Lua Snippets