Skip to main content

File Reading and Writing

IO Operations

The following example shows how to read, write and delete files on the file system.

Note: This assumes that there is a folder called C:\Temp. If that folder doesn't exist change the value of the filename variable to a location that does exist on your workstation.

-- The test file we're using, you will want to move it somewhere that exists.  Note that
-- two backslashes are required to escape that character.
local filename = "C:\\Temp\\test.lua"

-- Create a new file or overwrite the file if it exists and
-- write 1 line to it
file.Write(filename, "-- Line 1: This is a test comment.")

-- Read the entire file into a string
local buf = file.Read(filename)

if (buf == null) then
    ui.ConsoleLog("buf was null.")
end

-- Log it to the console.
ui.Log("Read 1")
ui.Log(buf)

-- This is a 2nd line we will append to the previous file.
file.Append(filename, "\r\n-- Line 2: This is a test comment.")

-- Re-read the entire file and log it to the console
buf = file.Read(filename)
ui.Log("Read 2")
ui.Log(buf)

-- Delete the old file
file.Delete(filename)

-- Create a file with 10 lines, then loop over each line.
buf = ""

for i = 1, 10 do
   buf = buf .. "Line " .. i .. "\r\n"
end

file.Write(filename, buf)

-- Read as an array of lines
local lines = file.ReadLines(filename)

for _, line in ipairs(lines) do
    ui.Log(line)
end

-- Delete the file we tested with.
file.Delete(filename)

ui.Log("Complete")
Last Modified: 06/29/2023