Home > Net >  How to read CSV files in lua
How to read CSV files in lua

Time:07-20

I am trying to read a .csv file that has length and quantity columns. I am able to read the first column ( 12.5, 10, 8....) but the quantity field is always empty. I am obviously new to lua and was wondering if anyone had an idea as to why by quantity is always empty.

function ReadFileNameWindows(PassedInWindowsPath)
local fileList = {}
for line in io.lines(PassedInWindowsPath) do
local length,quantity = line:match("%s*(.-),%s*(.-)")
    print(length)
    print(quantity)
    fileList[#fileList   1] = { length = length, quantity = quantity } 
    end

CodePudding user response:

I would suggest not write new code for that purpose. There are a a lot of code available with really permissive licenses. I personally use lua-csv which can be used like this:

local Csv  = require("csv.lua")
local File = Csv.open(Filename)
-- Parse all the lines
if File then
  for Line in File:lines() do
    for Index = 1, #Line do
      print("COL", Index, Line[Index])
    end
  end
  -- Close file
  File:close()
else
  print("ERROR:", Filename)
end

CodePudding user response:

Your pattern is wrong. line:match("%s*(.-),%s*(.-)") will first consume some spacing, then match some characters until the first ,, then again match some spacing, then match nothing (the empty string). That's because .- is a lazy match: It matches as little as possible (can be zero characters) for the pattern to match. As nothing comes after (.-), it will always match the empty string.

To fix this, simply use the greedy quantifier * (zero or more occurrences). line:match("%s*(.-),%s*(.*)"). This will match anything after the spacing after the first comma to the end of the string.

Furthermore, if you want to trim trailing spacing, use line:match("%s*(.-),%s*(.-)%s*$"). Note that I've changed .* back to .- since now there is %s*$ after it which must match: $ anchors the pattern at the end of the line, meaning .- can't stop matching early; %s* consumes all trailing spacing before the end of the line.

Reading CSV is easy enough that you probably won't need a library for it.

  • Related