Write to a file

Verified
Added by iNTERFACEWARE

How to open a file and write (replace file content), or append data (keep file content)

Source Code
   -- Write new content in a file - previous content is lost
   
   -- get a file handle - using overwrite mode
   local f = io.open('test2', 'w')
   f:write('This replaces previous text in the file')
   -- close the file handle
   f:close()
   
   -- read file to confirm data is overwritten
   local f = io.open('test2')   
   f:read('*a')
   f:close()
   
   
   -- Append content to a file - previous content is kept
   
   -- get a file handle - using append mode
   local f = io.open('test2', 'a')
   f:write(' - this is appended')
   -- close the file handle
   f:close()
   
   -- read file to confirm data is appended
   local f = io.open('test2')   
   f:read('*a')
   f:close()
Description
How to open a file and write (replace file content), or append data (keep file content)
Usage Details

There are three steps to write to a file: Open the file, use the returned file handle to write to the file, then close the file. You can open the file in write mode which replaces the current file contents, or append mode which retains the content.

How to use the snippet:

  • Paste the code for the desired file write method into your script