← Back to Lua Course | Chapter 8: File I/O | Lesson 1 of 7

Opening and closing files

io.open gives you a file handle, and you must close it when you are done.

Opening and closing files

io.open(path, mode) returns a file handle, or nil plus an error message and code if it fails. Modes are "r" to read, "w" to write and truncate, "a" to append, and the "r+", "w+" and "a+" variants for both, with "b" added for binary. Always call close, which flushes buffered data and frees the handle.

Note: Check the result of io.open before using it, because failure is returned rather than raised.

Example: Opening and closing files

lua
local f = assert(io.open("/tmp/lua_demo_open.txt", "w"))
print(io.type(f))
f:write("hello")
f:close()
print(io.type(f))
print(io.type(42))

-- Output:
-- file
-- closed file
-- nil
Common Mistakes
  1. Forgetting to close the file and losing buffered data
  2. Using the handle when io.open returned nil
  3. Opening with "w" and erasing an existing file by accident
Chapter Summary
  • io.open returns a handle or nil plus a message
  • Modes are r w a and plus variants
  • close flushes and releases the file
  • "w" truncates existing content
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.