Opening Files
io.open() is used to open a file according to a mode you specify. It returns a new file handle, or in case of an error, nil plus an error message.
-- Open file for read
local File = io.open("myFile.txt")
local Content = File:read('*a')
File:close()
In order to open the file make sure you are passing in the file path (location) and filename. Note we are also using Reading Files to read the contents and once finished, Closing File Connections to close the file.
In the above example, we opened the file in the default “r“ read mode, because a 2nd argument wasn’t provided to specify a different mode.
The specified mode enables you to open the file according to how you need to manipulate its contents.
“r“ | read (the default) |
“w“ | write or create if the file doesn't exist |
“a“ | append to the file. |
Plus “+“ allows read and write access to a file, can be used in combination with “r“, “w“ or “a“. Binary “b“ treats the file as a binary and can also be used in combination with “r“, “w“ or “a“. | |
"r+" or “rb+” | update while preserving all previous data. |
"w+" or “wb+“ | updates and erases previous data or creates |
"a+" or “ab+“ | append & update, the previous data is preserved, new data is only written at the end of the file. |