Writing to files
The write method saves strings and numbers to a file without adding newlines.
In this page:
Writing to files
file:write accepts any number of strings and numbers and writes them exactly as given, so include \n yourself. It returns the file handle so calls can be chained. Numbers are converted using the usual format, and other types must be converted with tostring first.
Note:
Use string.format together with write for tidy, structured lines.
Example: Writing to files
local path = "/tmp/lua_demo_write.txt"
local f = assert(io.open(path, "w"))
f:write("line one\n")
f:write("line ", 2, "\n"):write(string.format("pi is %.2f\n", math.pi))
f:close()
local r = assert(io.open(path, "r"))
print(r:read("a"))
r:close()
-- Output:
-- line one
-- line 2
-- pi is 3.14
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting write to add a newline
- Passing a table or nil to write
- Using a dot instead of a colon in f.write("x")
Chapter Summary
- write does not add newlines
- It accepts strings and numbers
- It returns the file for chaining
- Use the colon syntax f:write
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: