Opening and closing files
io.open gives you a file handle, and you must close it when you are done.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to close the file and losing buffered data
- Using the handle when io.open returned nil
- 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: