Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 32 ยท Standard Library and Tools

Files and I/O

Learn Lua file handling: io.open modes, read formats, lines, write and close, io.lines, plus the os library for time, dates, clock and environment variables.

Programs become useful when they can read data in and write results out. Lua's io library covers files, standard input and standard output with a small, consistent API, and the os library adds the clock, dates, environment variables and a few file operations.

In this lesson you will open files safely, choose the right read format, write text, loop over lines, and use os.time, os.date, os.clock and os.getenv. You will also see the 5.4 feature that closes files for you. Because failures are common with files, it helps to have read Error Handling first.

Lua is not installed on this site and the in-browser sandbox has no real files, so the Lua listings are read-only. The runnable examples are JavaScript stand-ins that model a file as a string with a read position.

The file workflow

Open io.open returns a handle or nil plus a message.
Read or write Use methods on the handle.
Close Flushes data and frees the handle.
1 / 2

Opening a file

io.open(name, mode) returns a file handle. If it fails (the file does not exist, you lack permission), it does not raise an error. It returns nil, a message and an error code, so you must check:

LUA
local file, err = io.open("notes.txt", "r")
if not file then
  print("cannot open: " .. err)
  return
end

When the file is missing, err reads like notes.txt: No such file or directory. The exact wording comes from your operating system. The mode string works like the C fopen modes:

Mode Meaning
"r" Read (default). The file must exist.
"w" Write. Creates the file or erases its content.
"a" Append. Creates the file if needed and writes at the end.
"r+" Read and write an existing file.
"w+" Read and write, erasing existing content.
"a+" Read and append.

Add b (as in "rb") for binary mode; it matters on Windows, where text mode translates line endings. Using assert is the quickest way to turn a failed open into an error: local file = assert(io.open("notes.txt")).

Reading

Methods are called with a colon on the handle: file:read(format). The formats in Lua 5.4 are:

  • "l" reads the next line and drops the newline. At end of file it returns nil. This is the default.
  • "L" reads the next line but keeps the newline.
  • "n" reads a number (integer or float) and returns nil if the next characters are not a number.
  • "a" reads the whole rest of the file. At end of file it returns the empty string "", never nil.
  • A number n reads up to n bytes, or nil at end of file. read(0) tests for end of file: it returns "" when more data exists and nil otherwise.

You can give several formats in one call, and get one result per format:

LUA
local file = assert(io.open("data.txt", "r"))
local title = file:read("l")
local count = file:read("n")
local rest  = file:read("a")
file:close()
print(title, count, #rest)

If data.txt contained the lines Report, 3 and a, b, c, the call to read("n") stops right after the digit, so rest begins with the newline that follows it. This is a common surprise: after reading a number, the line break is still waiting, and the next read("l") returns an empty line.

Looping over lines

The lines method returns an iterator that yields one line per step, which is how you normally process a file:

LUA
local file = assert(io.open("data.txt"))
for line in file:lines() do
  print(#line, line)
end
file:close()

io.lines(filename) is shorter: it opens the file, loops, and closes it automatically when the loop ends. If the file cannot be opened it raises an error instead of returning nil.

LUA
local total = 0
for line in io.lines("numbers.txt") do
  total = total + tonumber(line)
end
print(total)

You can pass formats to lines too, for example io.lines("numbers.txt", "n") to read numbers directly.

JS A file modelled as a string

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Writing

file:write(...) accepts strings and numbers (no automatic separators or newlines, unlike print) and returns the file itself, so calls can be chained. Use "w" to replace a file and "a" to add to it:

LUA
local out = assert(io.open("log.txt", "a"))
out:write("started at ", os.time(), "\n")
out:write(string.format("%-10s %5.2f\n", "total", 12.5))
out:close()

Output is buffered, so data may sit in memory until you call file:flush() or file:close(). Always close what you open; a handle that is never closed may lose its last writes if the program crashes. The standard streams are ready to use: io.write(...) writes to standard output, io.read(...) reads from standard input, and io.stderr:write(...) is the right place for error messages. Compare print, which adds tabs between arguments and a newline at the end, and always uses tostring.

Closing automatically

In Lua 5.4, file handles support the <close> attribute from Error Handling, so the file is closed when the scope ends, even if an error occurs:

LUA
do
  local file <close> = assert(io.open("data.txt"))
  print(file:read("l"))
end  -- closed here

Moving around a file

file:seek(whence, offset) moves the read/write position and returns the new position. whence is "set" (from the start), "cur" (from where you are) or "end". A handy idiom for getting a file's size is file:seek("end").

LUA
local file = assert(io.open("data.txt", "rb"))
local size = file:seek("end")
file:seek("set", 0)
local all = file:read("a")
print(size == #all)
file:close()

The os library

os talks to the operating system and the clock.

  • os.time() returns the current time as a number of seconds since the epoch (on most systems, January 1, 1970 UTC). os.time{year=2030, month=1, day=15, hour=12} converts a table to a timestamp; hour defaults to 12 and the other time fields to 0.
  • os.date(format, time) formats a timestamp. It uses strftime codes, such as "%Y-%m-%d" for 2030-01-15. A leading ! means UTC. The format "*t" returns a table with fields year, month, day, hour, min, sec, wday, yday and isdst.
  • os.clock() returns the CPU time the program has used, in seconds, as a float. Subtract two readings to time a piece of code.
  • os.getenv("HOME") returns an environment variable or nil if it is not set.
  • os.remove(name) and os.rename(old, new) delete and rename files, returning nil plus a message on failure. os.tmpname() gives a temporary file name, and os.exit(code) ends the program.
  • os.difftime(t2, t1) is the difference in seconds between two timestamps.
LUA
local t = os.time{year = 2030, month = 1, day = 15, hour = 12}
print(os.date("!%Y-%m-%d", t + 86400))   -- one day later
print(os.date("*t", t).month)
local start = os.clock()
-- ... work ...
print(("took %.3f s"):format(os.clock() - start))
print(os.getenv("DOES_NOT_EXIST"))

Because the timestamp for midnight depends on your time zone, the date printed by the first line can differ by a day where your zone is far from UTC; the last line prints nil. Treat os.clock as a way to compare timings on one machine, not as a precise benchmark.

JS A tiny word counter over lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Not checking io.open. Calling file:read() on nil gives the confusing error attempt to index a nil value (local 'file'). Use assert(io.open(...)) or test the result.
  • Forgetting the colon. file.read("l") passes "l" as the handle. Use file:read("l").
  • Writing with "w" by accident. It erases the file the moment it opens. Use "a" to add to a file.
  • Expecting read("a") to return nil at the end. It returns "".
  • Assuming a path is relative to the script. Relative paths are relative to the current directory where the program was started.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does io.open("missing.txt") return when the file does not exist?

    io.open reports failure through its return values, so you must check the result or wrap it in assert.
  2. 2. Which format reads a line and keeps the trailing newline?

    Lowercase l drops the newline, uppercase L keeps it. a reads everything left and n reads a number.
  3. 3. What does file:read("a") return at the end of the file?

    The a format always returns a string, which is empty when nothing is left. The line and count formats return nil instead.
  4. 4. Which mode erases an existing file as soon as it is opened?

    w creates the file or truncates it to zero length. Use a to append.
  5. 5. What is the advantage of for line in io.lines(name) over opening the file yourself?

    io.lines closes the file when the loop finishes. If the file cannot be opened it raises an error.

Summary

  • io.open(name, mode) returns a handle, or nil, message, code on failure; check it or use assert.
  • read formats: "l", "L", "n", "a", or a byte count. read("a") returns "" at the end.
  • lines() and io.lines(name) iterate over lines; io.lines closes the file for you.
  • write accepts strings and numbers and returns the handle; close or flush to be sure data is saved.
  • local f <close> closes a file automatically in Lua 5.4.
  • os.time, os.date, os.clock and os.getenv give you time, formatted dates, CPU time and environment variables.

Next, learn how to search and transform text in String Patterns.