Advertisement
Guest User

Untitled

a guest
Jun 19th, 2015
1,095
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1.  
  2. module(..., package.seeall)
  3.  
  4. ---------------------------------------------------------------------
  5. local function split(str, sep)
  6. sep = sep or ','
  7. fields={}
  8. local matchfunc = string.gmatch(str, "([^"..sep.."]+)")
  9. if not matchfunc then return {str} end
  10. for str in matchfunc do
  11. table.insert(fields, str)
  12. end
  13. return fields
  14. end
  15.  
  16. ---------------------------------------------------------------------
  17. function read(path, sep, tonum)
  18. tonum = tonum or true
  19. sep = sep or ','
  20. local csvFile = {}
  21. local file = assert(io.open(path, "r"))
  22. for line in file:lines() do
  23. fields = split(line, sep)
  24. if tonum then -- convert numeric fields to numbers
  25. for i=1,#fields do
  26. fields[i] = tonumber(fields[i]) or fields[i]
  27. end
  28. end
  29. table.insert(csvFile, fields)
  30. end
  31. file:close()
  32. return csvFile
  33. end
  34.  
  35. ---------------------------------------------------------------------
  36. function write(path, data, sep)
  37. sep = sep or ','
  38. local file = assert(io.open(path, "w"))
  39. for i=1,#data do
  40. for j=1,#data[i] do
  41. if j>1 then file:write(sep) end
  42. file:write(data[i][j])
  43. end
  44. file:write('\n')
  45. end
  46. file:close()
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement