How to resolve the algorithm CSV data manipulation step by step in the Lua programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm CSV data manipulation step by step in the Lua programming language
Table of Contents
Problem Statement
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: Suggestions
Let's start with the solution:
Step by Step solution about How to resolve the algorithm CSV data manipulation step by step in the Lua programming language
Source code in the lua programming language
local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the Lua programming language
You may also check:How to resolve the algorithm Integer sequence step by step in the min programming language
You may also check:How to resolve the algorithm Conditional structures step by step in the 68000 Assembly programming language
You may also check:How to resolve the algorithm Generate lower case ASCII alphabet step by step in the Lua programming language
You may also check:How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Logtalk programming language