Guest User

csv-converter

a guest
Aug 7th, 2013
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. function read(csvFile)
  2. if fs.exists(csvFile) then
  3. local tLines = {}
  4. local h = fs.open(csvFile, "r")
  5. local lineCounter = 1
  6. while true do
  7. sLine = h.readLine()
  8. if not sLine then -- we reached the end of file
  9. break
  10. else
  11. tLines[lineCounter] = textutils.unserialize("{"..sLine.."}")
  12. end
  13. lineCounter = lineCounter+1
  14. end
  15. -- swap x and y in tLines and return
  16. local helperRows = #tLines[1]
  17. local helperCols = #tLines
  18. local tReturn = {}
  19. for i = 1, helperRows do
  20. tReturn[i] = {}
  21. for j = 1, helperCols do
  22. tReturn[i][j] = tLines[j][i]
  23. end
  24. end
  25. return tReturn
  26. else
  27. error("Could not find "..csvFile)
  28. end
  29. end
  30.  
  31. function write(tInput, csvFile)
  32. local tLines = {}
  33. -- swap x and y again
  34. local helperRows = #tInput[1]
  35. local helperCols = #tInput
  36. for i = 1, helperRows do
  37. tLines[i] = {}
  38. for j = 1, helperCols do
  39. tLines[i][j] = tInput[j][i]
  40. end
  41. end
  42. local h = fs.open(csvFile, "w")
  43. for i = 1, #tLines do
  44. -- format from "{[1]=value1,[2]=value2}" to "value1;value2;" and write to file
  45. sLine = textutils.serialize(tLines[i])
  46. sLine = sLine:sub(2, #sLine-1) --this removes "{" and "}"
  47. h.writeLine(string.gsub(sLine, "%[(%w+)]=(%x+),", "%2;"))
  48. -- this removes "[key]=", replaces "," with ";" and writes the line
  49. end
  50. h.close()
  51. end
Advertisement
Add Comment
Please, Sign In to add comment