How To | Read files using scripting

Learn how to use scripting to efficiently and effectively read files.

Updated at May 11th, 2023

Procedure


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

Tip

To learn how to write files using scripting, see the related article "How To | Write files using scripting"

 
--READING FILES
--Reading a File, Method 1
--The "Direct Way", Simple Model
io.input("design/MyTestFile")   --Open the file for reading     
thefile = io.read("*a")          --One way to do this
  --"a" means read the whole file.
  --The asterisk is optional in Lua 5.3 and beyond, but required in Lua 5.2 in before.
print ("This is Read Method #1, Entire File Read")
print (thefile)

--Or by line
print ("This is Read Method #1, Line-by-Line Read")
count = 0
for line in io.lines("design/MyTestFile") do
  count = count + 1
  print(count, line)
end
io.input("design/MyTestFile")   --Close file after use



--Reading a File, Method 2
  --The Complete I/O Model
  --use for advanced file manipulation, reading/writing to several files
myfile = io.open ("design/MyTestFile2","r")
  --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
  thefile = myfile:read("*a")
    --"a" means read the whole file.
    --The asterisk is optional in Lua 5.3 and beyond, but required in Lua 5.2 in before.
  print("This is Read Method #2")
  print(thefile)
  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