How To | Write files using scripting

Learn the basics of writing files using scripting and discover the advantages it can bring to your workflow.

Updated at June 8th, 2023

Procedure


There are two primary methods of writing (and reading) files via scripted methods: a Simple Method and a Complete I/O Model:

Tip

To learn how to read files using scripting, see the related article "How To | Read files using scripting"

 
--WRITING FILES
--Writing a File, Method 1
--The "Direct Way", Simple Model
Info = "Whatever I want\r\n"
io.output("design/MyTestFile")  --Create the file for writing to 
io.write(Info)                  --Write to the File
io.write("More stuff\r\n")        --Append more
io.close()                      --Close the file

--Writing a File, Method 2
  --The Complete I/O Model
  --use for advanced file manipulation, reading/writing to several files
Info = "A different method\r\n"
myfile = io.open ("design/MyTestFile2","w+")
  --r for Read-Only of existing file
  --w for Create/Write new file
  --a for Append Mode, this is for Writing only
  --r+ for Read/Write existing file, will overwrite existing content
  --w+, same as "w", except reading is also allowed
  --a+, same as "a", except reading is also allowed
if myfile~=nil then
 filedata = myfile:write(Info)
 filedata = myfile:write("Adding some more\r\n")
  print("File #2 has been written")
  io.close(myfile)              --Close file after use
else
  print("myfile==nil")
  --for certain argument usages a nil is returned if file does not exist
end

--The locations "design/" and "media/" are acceptable.
--The "media/" folder is generally for all media files, and the "design/" folder
--is where uncompressed design configuration files reside.
--Files in "design/" can be viewed at http://[ip of core]/designs/current_design