CSV data manipulation: Difference between revisions

Content added Content deleted
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 27: Line 27:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>L(=line) File(‘data.csv’).read_lines()
<syntaxhighlight lang=11l>L(=line) File(‘data.csv’).read_lines()
I L.index == 0
I L.index == 0
line ‘’= ‘,SUM’
line ‘’= ‘,SUM’
E
E
line ‘’= ‘,’sum(line.split(‘,’).map(Int))
line ‘’= ‘,’sum(line.split(‘,’).map(Int))
print(line)</lang>
print(line)</syntaxhighlight>


{{out}}
{{out}}
Line 47: Line 47:
Ada has no build-in or predefined functions to read or write CSV tables. We thus define a (very simplistic) package CSV, which allows to read a row (function Line), to step from column to column (function Next), and to get the items in the column (function Item):
Ada has no build-in or predefined functions to read or write CSV tables. We thus define a (very simplistic) package CSV, which allows to read a row (function Line), to step from column to column (function Next), and to get the items in the column (function Item):


<lang Ada>package CSV is
<syntaxhighlight lang=Ada>package CSV is
type Row(<>) is tagged private;
type Row(<>) is tagged private;
Line 65: Line 65:
Sep: Character;
Sep: Character;
end record;
end record;
end CSV;</lang>
end CSV;</syntaxhighlight>


The implementation of the package is
The implementation of the package is


<lang Ada>package body CSV is
<syntaxhighlight lang=Ada>package body CSV is
function Line(S: String; Separator: Character := ',')
function Line(S: String; Separator: Character := ',')
Line 92: Line 92:
end Next;
end Next;
end CSV;</lang>
end CSV;</syntaxhighlight>


Finally, the main program which uses the package CSV:
Finally, the main program which uses the package CSV:


<lang Ada>with CSV, Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang=Ada>with CSV, Ada.Text_IO; use Ada.Text_IO;


procedure CSV_Data_Manipulation is
procedure CSV_Data_Manipulation is
Line 114: Line 114:
end;
end;
end loop;
end loop;
end CSV_Data_Manipulation;</lang>
end CSV_Data_Manipulation;</syntaxhighlight>


{{out}}
{{out}}
Line 126: Line 126:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang=aime>void
read_csv(list t, text path)
read_csv(list t, text path)
{
{
Line 198: Line 198:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
<pre>C1,C2,C3,C4,C5,SUM
Line 207: Line 207:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68># count occurrances of a char in string #
<syntaxhighlight lang=algol68># count occurrances of a char in string #
PROC char count = (CHAR c, STRING str) INT:
PROC char count = (CHAR c, STRING str) INT:
BEGIN
BEGIN
Line 294: Line 294:
print ((join (fields, ","), new line))
print ((join (fields, ","), new line))
OD;
OD;
close (foo)</lang>
close (foo)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 306: Line 306:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>; data.csv
<syntaxhighlight lang=rebol>; data.csv
;
;
; C1,C2,C3,C4,C5
; C1,C2,C3,C4,C5
Line 328: Line 328:
prints pad column 6
prints pad column 6
print ""
print ""
]</lang>
]</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Loop, Read, Data.csv
<syntaxhighlight lang=AutoHotkey>Loop, Read, Data.csv
{
{
i := A_Index
i := A_Index
Line 337: Line 337:
Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? "`n" : ",")
Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? "`n" : ",")
}
}
FileAppend, %Output%, NewData.csv</lang>
FileAppend, %Output%, NewData.csv</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>C1,C2,C3,C4,C5
<pre>C1,C2,C3,C4,C5
Line 347: Line 347:
=={{header|AWK}}==
=={{header|AWK}}==
adds a column sum to a csv table
adds a column sum to a csv table
<lang AWK>#!/usr/bin/awk -f
<syntaxhighlight lang=AWK>#!/usr/bin/awk -f
BEGIN { FS = OFS = "," }
BEGIN { FS = OFS = "," }
NR==1 {
NR==1 {
Line 359: Line 359:
}
}
print $0, sum
print $0, sum
}</lang>
}</syntaxhighlight>
<pre>awk -f csv_data_manipulation.awk data.csv
<pre>awk -f csv_data_manipulation.awk data.csv
C1,C2,C3,C4,C5,SUM
C1,C2,C3,C4,C5,SUM
Line 369: Line 369:
=={{header|BaCon}}==
=={{header|BaCon}}==
Load the data, change a value and add a column with totals. Then save and print.
Load the data, change a value and add a column with totals. Then save and print.
<lang BaCon>OPTION COLLAPSE TRUE
<syntaxhighlight lang=BaCon>OPTION COLLAPSE TRUE
OPTION DELIM ","
OPTION DELIM ","


Line 388: Line 388:
SAVE total$ TO "data.csv"
SAVE total$ TO "data.csv"
PRINT total$
PRINT total$
</syntaxhighlight>
</lang>
<pre>
<pre>
C1,C2,C3,C4,C5,SUM
C1,C2,C3,C4,C5,SUM
Line 403: Line 403:
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang qbasic>OPEN "manip.csv" FOR INPUT AS #1
<syntaxhighlight lang=qbasic>OPEN "manip.csv" FOR INPUT AS #1
OPEN "manip2.csv" FOR OUTPUT AS #2
OPEN "manip2.csv" FOR OUTPUT AS #2


Line 416: Line 416:


CLOSE #1, #2
CLOSE #1, #2
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 423: Line 423:


=={{header|BQN}}==
=={{header|BQN}}==
<lang bqn>
<syntaxhighlight lang=bqn>


csvstr ← ⟨"C1,C2,C3,C4,C5", "1,5,9,13,17", "2,6,10,14,18", "3,7,11,15,19", "4,8,12,16,20"⟩
csvstr ← ⟨"C1,C2,C3,C4,C5", "1,5,9,13,17", "2,6,10,14,18", "3,7,11,15,19", "4,8,12,16,20"⟩
Line 432: Line 432:
sums ← ⟨"SUMS"⟩ ∾+´˘ 1↓ intdata
sums ← ⟨"SUMS"⟩ ∾+´˘ 1↓ intdata
done ← sums ∾˜˘ intdata
done ← sums ∾˜˘ intdata
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=c>
<lang c>


#define TITLE "CSV data manipulation"
#define TITLE "CSV data manipulation"
Line 712: Line 712:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out|Output (in <tt>tmp/csv-data-manipulation.result.csv</tt>)}}
{{out|Output (in <tt>tmp/csv-data-manipulation.result.csv</tt>)}}
<pre>
<pre>
Line 723: Line 723:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System.IO;
<syntaxhighlight lang=csharp>using System.IO;
using System.Linq;
using System.Linq;


Line 744: Line 744:
}
}
}
}
</syntaxhighlight>
</lang>
{{out|Output (in <tt>test_out.csv</tt>)}}
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
<pre>
Line 755: Line 755:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <map>
<syntaxhighlight lang=cpp>#include <map>
#include <vector>
#include <vector>
#include <iostream>
#include <iostream>
Line 883: Line 883:
oCSV.save( "test_out.csv" );
oCSV.save( "test_out.csv" );
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out|Output (in <tt>test_out.csv</tt>)}}
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
<pre>
Line 894: Line 894:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>
<syntaxhighlight lang=clojure>
(require '[clojure.data.csv :as csv]
(require '[clojure.data.csv :as csv]
'[clojure.java.io :as io])
'[clojure.java.io :as io])
Line 909: Line 909:
(with-open [out-file (io/writer "test_out.csv")]
(with-open [out-file (io/writer "test_out.csv")]
(csv/write-csv out-file out-data)))))
(csv/write-csv out-file out-data)))))
</syntaxhighlight>
</lang>


{{out|Output (in <code>test_out.csv</code>)}}
{{out|Output (in <code>test_out.csv</code>)}}
Line 923: Line 923:
Using tech.ml.dataset
Using tech.ml.dataset


<lang clojure>
<syntaxhighlight lang=clojure>
(require '[tech.v3.dataset :as ds]
(require '[tech.v3.dataset :as ds]
'[tech.v3.datatype.functional :as dfn])
'[tech.v3.datatype.functional :as dfn])
Line 934: Line 934:


(ds/write! (add-sum (ds/->dataset "resources/input.csv")) "resources/output.csv")
(ds/write! (add-sum (ds/->dataset "resources/input.csv")) "resources/output.csv")
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang COBOL>
<syntaxhighlight lang=COBOL>
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. CSV.
PROGRAM-ID. CSV.
Line 1,031: Line 1,031:
END-PROGRAM.
END-PROGRAM.
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Used only built-in functions which are in the standard. There are widespread libraries for working with csv (which can be easily loaded via quicklisp). As another example, I didn't use a split-string function, even though it is available in some implementations and in many compatibility layers and libraries. Instead, I formatted the csv file into s-expressions for the reader to understand it. Also, it deserves a mention that Common Lisp has built-in arrays, but for so little data it is easier to use nested lists.
Used only built-in functions which are in the standard. There are widespread libraries for working with csv (which can be easily loaded via quicklisp). As another example, I didn't use a split-string function, even though it is available in some implementations and in many compatibility layers and libraries. Instead, I formatted the csv file into s-expressions for the reader to understand it. Also, it deserves a mention that Common Lisp has built-in arrays, but for so little data it is easier to use nested lists.


<lang lisp>
<syntaxhighlight lang=lisp>
(defun csvfile-to-nested-list (filename delim-char)
(defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
"Reads the csv to a nested list, where each sublist represents a line."
Line 1,076: Line 1,076:
result-header (nested-list-to-csv data-list ",")))))
result-header (nested-list-to-csv data-list ",")))))
(main)
(main)
</syntaxhighlight>
</lang>


{{out|Output (in <code>results.txt</code>)}}
{{out|Output (in <code>results.txt</code>)}}
Line 1,088: Line 1,088:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang=d>void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
std.algorithm, std.conv, std.range;
Line 1,097: Line 1,097:
fout.writef("%(%(%d,%)\n%)", rows.dropOne
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}</lang>
}</syntaxhighlight>
{{out|Output (in <code>csv_data_out.csv</code>)}}
{{out|Output (in <code>csv_data_out.csv</code>)}}
<pre>C1,C2,C3,C4,C5
<pre>C1,C2,C3,C4,C5
Line 1,109: Line 1,109:
{{libheader| System.Types}}
{{libheader| System.Types}}
{{Trans|C#}}
{{Trans|C#}}
<lang Delphi>
<syntaxhighlight lang=Delphi>
program CSV_data_manipulation;
program CSV_data_manipulation;


Line 1,155: Line 1,155:
end;
end;
TFile.WriteAllLines(FILENAME, Input);
TFile.WriteAllLines(FILENAME, Input);
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
<pre>C1,C2,C3,C4,C5,SUM
Line 1,163: Line 1,163:
4,8,12,16,20,60</pre>
4,8,12,16,20,60</pre>
=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang=scheme>
;; CSV -> LISTS
;; CSV -> LISTS
(define (csv->row line) (map (lambda(x) (or (string->number x) x)) (string-split line ",")))
(define (csv->row line) (map (lambda(x) (or (string->number x) x)) (string-split line ",")))
Line 1,185: Line 1,185:
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang scheme>
<syntaxhighlight lang=scheme>
(define file.csv #<<
(define file.csv #<<
C1,C2,C3,C4,C5
C1,C2,C3,C4,C5
Line 1,203: Line 1,203:
3,7,11,15,19,55
3,7,11,15,19,55
4,8,12,16,20,60"
4,8,12,16,20,60"
</syntaxhighlight>
</lang>


=={{header|ECL}}==
=={{header|ECL}}==
<lang>// Assumes a CSV file exists and has been sprayed to a Thor cluster
<syntaxhighlight lang=text>// Assumes a CSV file exists and has been sprayed to a Thor cluster
MyFileLayout := RECORD
MyFileLayout := RECORD
STRING Field1;
STRING Field1;
Line 1,226: Line 1,226:


MyNewDataset := PROJECT(MyDataset,Appended(LEFT));
MyNewDataset := PROJECT(MyDataset,Appended(LEFT));
OUTPUT(myNewDataset,,'~Rosetta::myNewCSVFile',CSV,OVERWRITE);</lang>
OUTPUT(myNewDataset,,'~Rosetta::myNewCSVFile',CSV,OVERWRITE);</syntaxhighlight>
{{Out}} (contents of Rosetta::myNewCSVFile):
{{Out}} (contents of Rosetta::myNewCSVFile):
<pre>C1x,C2y,C3z,C4a,C5b
<pre>C1x,C2y,C3z,C4a,C5b
Line 1,235: Line 1,235:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang Elixir>
<syntaxhighlight lang=Elixir>
defmodule Csv do
defmodule Csv do
defstruct header: "", data: "", separator: ","
defstruct header: "", data: "", separator: ","
Line 1,287: Line 1,287:
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
|> Csv.to_file("out.csv")
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 1,299: Line 1,299:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang Erlang>
<syntaxhighlight lang=Erlang>
-module( csv_data ).
-module( csv_data ).


Line 1,336: Line 1,336:
split( 1, List ) -> {[], List};
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
split( N, List ) -> lists:split( N - 1, List ).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,349: Line 1,349:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>--- Read CSV file and add columns headed with 'SUM'
<syntaxhighlight lang=euphoria>--- Read CSV file and add columns headed with 'SUM'
--- with trace
--- with trace
-- trace(0)
-- trace(0)
Line 1,440: Line 1,440:


main()
main()
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,453: Line 1,453:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System.IO
<syntaxhighlight lang=fsharp>open System.IO


[<EntryPoint>]
[<EntryPoint>]
Line 1,467: Line 1,467:
File.WriteAllLines ("test_out.csv", output)
File.WriteAllLines ("test_out.csv", output)
0
0
</syntaxhighlight>
</lang>
{{out|Output (in <tt>test_out.csv</tt>)}}
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
<pre>
Line 1,479: Line 1,479:
=={{header|Factor}}==
=={{header|Factor}}==
The <code>csv</code> vocabulary provides words for working with csv files, strings, and streams.
The <code>csv</code> vocabulary provides words for working with csv files, strings, and streams.
<lang factor>USING: csv io.encodings.utf8 kernel math.parser sequences ;
<syntaxhighlight lang=factor>USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
IN: rosetta-code.csv-manipulation


Line 1,488: Line 1,488:
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;


"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi</lang>
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi</syntaxhighlight>
{{out}}
{{out}}
Contents of <code>example.csv</code>
Contents of <code>example.csv</code>
Line 1,500: Line 1,500:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>\ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues
<syntaxhighlight lang=forth>\ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues
\ USAGE:
\ USAGE:
\ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv
\ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv
Line 1,548: Line 1,548:
THEN
THEN
2DROP 2DROP
2DROP 2DROP
;</lang>
;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,561: Line 1,561:
It's fairly easy to read arbitrary lines using allocatable character strings, available since Fortran 2003.
It's fairly easy to read arbitrary lines using allocatable character strings, available since Fortran 2003.


<lang fortran>program rowsum
<syntaxhighlight lang=fortran>program rowsum
implicit none
implicit none
character(:), allocatable :: line, name, a(:)
character(:), allocatable :: line, name, a(:)
Line 1,667: Line 1,667:
array(p) = line(k:n)
array(p) = line(k:n)
end subroutine
end subroutine
end program</lang>
end program</syntaxhighlight>


=== Old Fortran ===
=== Old Fortran ===
Line 1,680: Line 1,680:
Another F90 feature is the SUM function that adds the elements of an array span. Even though for the example the first column looks rather like a record number, all five columns will be added, but otherwise the statement would be SUM(X(2:N)). Other modifications can be made without much difficulty, if desired. The output format is I0 rather than say I2, as it provides only the needed number of characters to present the integer's value. There is no corresponding F format code, and free-format output would roll out many spaces as padding in case of large numbers, that are not present here. It would be needed for a more general solution, but for this example, I0 will do.
Another F90 feature is the SUM function that adds the elements of an array span. Even though for the example the first column looks rather like a record number, all five columns will be added, but otherwise the statement would be SUM(X(2:N)). Other modifications can be made without much difficulty, if desired. The output format is I0 rather than say I2, as it provides only the needed number of characters to present the integer's value. There is no corresponding F format code, and free-format output would roll out many spaces as padding in case of large numbers, that are not present here. It would be needed for a more general solution, but for this example, I0 will do.


<lang Fortran>
<syntaxhighlight lang=Fortran>
Copies a file with 5 comma-separated values to a line, appending a column holding their sum.
Copies a file with 5 comma-separated values to a line, appending a column holding their sum.
INTEGER N !Instead of littering the source with "5"
INTEGER N !Instead of littering the source with "5"
Line 1,701: Line 1,701:
10 CLOSE (IN) !All done.
10 CLOSE (IN) !All done.
END !That's all.
END !That's all.
</syntaxhighlight>
</lang>
Output could of course be written to a disc file instead of a screen, but here it is:
Output could of course be written to a disc file instead of a screen, but here it is:
<pre>
<pre>
Line 1,712: Line 1,712:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64


Open "manip.csv" For Input As #1 ' existing CSV file
Open "manip.csv" For Input As #1 ' existing CSV file
Line 1,731: Line 1,731:


Close #1
Close #1
Close #2</lang>
Close #2</syntaxhighlight>


{{out}}
{{out}}
Line 1,745: Line 1,745:


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>import io.{lines, PrintWriter}
<syntaxhighlight lang=funl>import io.{lines, PrintWriter}


data Table( header, rows )
data Table( header, rows )
Line 1,789: Line 1,789:
t = addColumn( read('test.csv'), 'SUM', r -> r('SUM') = sum(int(v) | (_, v) <- r if v != null) )
t = addColumn( read('test.csv'), 'SUM', r -> r('SUM') = sum(int(v) | (_, v) <- r if v != null) )
write( t, 'test_out.csv' )
write( t, 'test_out.csv' )
write( t, System.out )</lang>
write( t, System.out )</syntaxhighlight>


{{out}}
{{out}}
Line 1,802: Line 1,802:


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Form_Open()
<syntaxhighlight lang=gambas>Public Sub Form_Open()
Dim sData As String = File.Load("data.csv")
Dim sData As String = File.Load("data.csv")
Dim sLine, sTemp As String
Dim sLine, sTemp As String
Line 1,833: Line 1,833:
File.Save(User.home &/ "CSVData.csv", sData)
File.Save(User.home &/ "CSVData.csv", sData)


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,844: Line 1,844:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 1,901: Line 1,901:
log.Fatal(err)
log.Fatal(err)
}
}
}</lang>
}</syntaxhighlight>
{{in|sample.csv}}
{{in|sample.csv}}
<pre>
<pre>
Line 1,920: Line 1,920:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def csv = []
<syntaxhighlight lang=groovy>def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
Line 1,927: Line 1,927:
csv[0][0] = 'Column0'
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')</lang>
saveCsv new File('csv_out.txt')</syntaxhighlight>


csv_out.txt:
csv_out.txt:
Line 1,940: Line 1,940:
Array-based solution:
Array-based solution:


<lang haskell>import Data.Array (Array(..), (//), bounds, elems, listArray)
<syntaxhighlight lang=haskell>import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Data.List (intercalate)
import Control.Monad (when)
import Control.Monad (when)
Line 1,984: Line 1,984:
main = do
main = do
a <- fieldsFromFile "example.txt"
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a</lang>
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a</syntaxhighlight>


'''Solution 2'''
'''Solution 2'''
List-based solution, heavily using functors and lenses
List-based solution, heavily using functors and lenses
<lang haskell>{-# LANGUAGE FlexibleContexts,
<syntaxhighlight lang=haskell>{-# LANGUAGE FlexibleContexts,
TypeFamilies,
TypeFamilies,
NoMonomorphismRestriction #-}
NoMonomorphismRestriction #-}
Line 2,036: Line 2,036:
\2, 6, 10, 14, 18\n\
\2, 6, 10, 14, 18\n\
\3, 7, 11, 15, 19\n\
\3, 7, 11, 15, 19\n\
\4, 8, 12, 16, 20"</lang>
\4, 8, 12, 16, 20"</syntaxhighlight>


Examples:
Examples:
Line 2,090: Line 2,090:


3. Construction and combination
3. Construction and combination
<lang haskell>sampleSum = sample <||> (mkRow ["SUM"] <==> mkColumn sums)
<syntaxhighlight lang=haskell>sampleSum = sample <||> (mkRow ["SUM"] <==> mkColumn sums)
where sums = map (show . sum) (read <$$> drop 1 (values sample))</lang>
where sums = map (show . sum) (read <$$> drop 1 (values sample))</syntaxhighlight>


<pre>λ> sampleSum
<pre>λ> sampleSum
Line 2,104: Line 2,104:
This version only works in Unicon, but can be easily adapted to work in Icon.
This version only works in Unicon, but can be easily adapted to work in Icon.


<lang unicon>import Utils # To get CSV procedures
<syntaxhighlight lang=unicon>import Utils # To get CSV procedures


procedure main(A)
procedure main(A)
Line 2,114: Line 2,114:
write(encodeCSV(csv))
write(encodeCSV(csv))
}
}
end</lang>
end</syntaxhighlight>


Sample run:
Sample run:
Line 2,131: Line 2,131:
Like other languages it is not necessary to use the csv utilities to accomplish this task.
Like other languages it is not necessary to use the csv utilities to accomplish this task.


<lang j> data=: (','&splitstring);.2 freads 'rc_csv.csv' NB. read and parse data
<syntaxhighlight lang=j> data=: (','&splitstring);.2 freads 'rc_csv.csv' NB. read and parse data
data=: (<'"spam"') (<2 3)} data NB. amend cell in 3rd row, 4th column (0-indexing)
data=: (<'"spam"') (<2 3)} data NB. amend cell in 3rd row, 4th column (0-indexing)
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data NB. format and write out amended data</lang>
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data NB. format and write out amended data</syntaxhighlight>


Using the [[j:Addons/tables/dsv|delimiter-separated-values utilities]] (of which <code>tables/csv</code> is a special case) will handle more complex csv constructs:
Using the [[j:Addons/tables/dsv|delimiter-separated-values utilities]] (of which <code>tables/csv</code> is a special case) will handle more complex csv constructs:


<lang j> require 'tables/csv'
<syntaxhighlight lang=j> require 'tables/csv'
data=: makenum readcsv 'rc_csv.csv' NB. read data and convert cells to numeric where possible
data=: makenum readcsv 'rc_csv.csv' NB. read data and convert cells to numeric where possible
data=: (<'spam') (2 3;3 0)} data NB. amend 2 cells
data=: (<'spam') (2 3;3 0)} data NB. amend 2 cells
data writecsv 'rc_outcsv.csv' NB. write out amended data. Strings are double-quoted</lang>
data writecsv 'rc_outcsv.csv' NB. write out amended data. Strings are double-quoted</syntaxhighlight>


Adding a column with the sum of the rows:
Adding a column with the sum of the rows:
<lang j> require 'tables/csv'
<syntaxhighlight lang=j> require 'tables/csv'
'hdr data'=: split readcsv 'rc_csv.csv' NB. read data, split the header & data
'hdr data'=: split readcsv 'rc_csv.csv' NB. read data, split the header & data
hdr=: hdr , <'SUM' NB. add title for extra column to header
hdr=: hdr , <'SUM' NB. add title for extra column to header
data=: <"0 (,. +/"1) makenum data NB. convert to numeric, sum rows & append column
data=: <"0 (,. +/"1) makenum data NB. convert to numeric, sum rows & append column
(hdr,data) writecsv 'rc_out.csv'</lang>
(hdr,data) writecsv 'rc_out.csv'</syntaxhighlight>


Tacit version of above:
Tacit version of above:
<lang j> sumCSVrows=: writecsv~ (((<'SUM') ,~ {.) , [: (<"0)@(,. +/"1) makenum@}.)@readcsv
<syntaxhighlight lang=j> sumCSVrows=: writecsv~ (((<'SUM') ,~ {.) , [: (<"0)@(,. +/"1) makenum@}.)@readcsv
'rc_out.csv' sumCSVrows 'rc.csv'</lang>
'rc_out.csv' sumCSVrows 'rc.csv'</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
===Roll Your Own===
===Roll Your Own===
<lang java>import java.io.*;
<syntaxhighlight lang=java>import java.io.*;
import java.awt.Point;
import java.awt.Point;
import java.util.HashMap;
import java.util.HashMap;
Line 2,258: Line 2,258:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out|Output (in <tt>test_out.csv</tt>)}}
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
<pre>
Line 2,270: Line 2,270:
{{libheader|Apache commons-csv}}
{{libheader|Apache commons-csv}}
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
<lang java>import java.io.*;
<syntaxhighlight lang=java>import java.io.*;
import java.util.*;
import java.util.*;


Line 2,395: Line 2,395:
}
}
}
}
</syntaxhighlight>
</lang>
{{in}} data/csvtest_in.csv
{{in}} data/csvtest_in.csv
<pre>
<pre>
Line 2,414: Line 2,414:
===uniVocity-parsers===
===uniVocity-parsers===
Using the [http://www.univocity.com/pages/parsers-tutorial uniVocity-parsers] library.
Using the [http://www.univocity.com/pages/parsers-tutorial uniVocity-parsers] library.
<lang java>
<syntaxhighlight lang=java>
public static void main(String[] args) throws IOException {
public static void main(String[] args) throws IOException {


Line 2,446: Line 2,446:
writer.writeRows(new ArrayList<List<Object>>());
writer.writeRows(new ArrayList<List<Object>>());
}
}
</syntaxhighlight>
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 2,454: Line 2,454:
As an embedded scripting language which evolved in browsers carefully isolated from local file systems, JavaScript has no standard file IO libraries. The readFile() and writeFile() functions used in this example are written for JS embedded in macOS as 'JavaScript for Automation'. Other embeddings will require other definitions of these functions, and in some JS contexts it will not be possible to write them at all.
As an embedded scripting language which evolved in browsers carefully isolated from local file systems, JavaScript has no standard file IO libraries. The readFile() and writeFile() functions used in this example are written for JS embedded in macOS as 'JavaScript for Automation'. Other embeddings will require other definitions of these functions, and in some JS contexts it will not be possible to write them at all.


<lang JavaScript>(function () {
<syntaxhighlight lang=JavaScript>(function () {
'use strict';
'use strict';


Line 2,529: Line 2,529:
);
);


})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,543: Line 2,543:
Below is a toy example to add new columns to an CSV file. Other manipulations, i.e. adding new rows, modifying existing values and so forth, can be accomplished very easily.
Below is a toy example to add new columns to an CSV file. Other manipulations, i.e. adding new rows, modifying existing values and so forth, can be accomplished very easily.


<lang javascript>const fs = require('fs');
<syntaxhighlight lang=javascript>const fs = require('fs');


// formats for the data parameter in the function below: {col1: array | function, col2: array | function}
// formats for the data parameter in the function below: {col1: array | function, col2: array | function}
Line 2,583: Line 2,583:
return idx;
return idx;
}
}
});</lang>
});</syntaxhighlight>


{{output}}
{{output}}
Line 2,599: Line 2,599:


The writing out of each line is facilitated by jq's @csv builtin. We must "slurp in" the file (using the -s option) so the header line can be handled specially.
The writing out of each line is facilitated by jq's @csv builtin. We must "slurp in" the file (using the -s option) so the header line can be handled specially.
<lang jq># Omit empty lines
<syntaxhighlight lang=jq># Omit empty lines
def read_csv:
def read_csv:
split("\n")
split("\n")
Line 2,613: Line 2,613:
([]; ($line|map(tonumber)) as $line | . + [$line + [$line|add]]))[] ] ;
([]; ($line|map(tonumber)) as $line | . + [$line + [$line|add]]))[] ] ;
read_csv | add_column("SUM") | map(@csv)[]</lang>
read_csv | add_column("SUM") | map(@csv)[]</syntaxhighlight>
{{Out}}
{{Out}}
$ jq -s -R -r -f CSV_data_manipulation.jq input.csv
$ jq -s -R -r -f CSV_data_manipulation.jq input.csv
Line 2,623: Line 2,623:


=={{header|Julia}}==
=={{header|Julia}}==
<lang Julia>using DataFrames, CSV
<syntaxhighlight lang=Julia>using DataFrames, CSV


ifn = "csv_data_manipulation_in.dat"
ifn = "csv_data_manipulation_in.dat"
Line 2,631: Line 2,631:
df.SUM = sum.(eachrow(df))
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
CSV.write(ofn, df)
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
$ cat csv_data_manipulation_out.dat
$ cat csv_data_manipulation_out.dat
Line 2,642: Line 2,642:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.3
<syntaxhighlight lang=scala>// version 1.1.3


import java.io.File
import java.io.File
Line 2,655: Line 2,655:
File("example2.csv").writeText(text) // write to new file
File("example2.csv").writeText(text) // write to new file
println(text) // print to console
println(text) // print to console
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,667: Line 2,667:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>----------------------------------------
<syntaxhighlight lang=lingo>----------------------------------------
-- Simplified CSV parser (without escape character support etc.).
-- Simplified CSV parser (without escape character support etc.).
-- First line is interrepted as header with column names.
-- First line is interrepted as header with column names.
Line 2,765: Line 2,765:
delete char (str.length-delim.length+1) to str.length of str
delete char (str.length-delim.length+1) to str.length of str
return str
return str
end</lang>
end</syntaxhighlight>


<lang lingo>sep = ","
<syntaxhighlight lang=lingo>sep = ","
eol = numtochar(10)
eol = numtochar(10)


Line 2,810: Line 2,810:
3,7,11,15,19,55
3,7,11,15,19,55
4,8,12,16,20,60
4,8,12,16,20,60
"</lang>
"</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Adds a SUM column.
Adds a SUM column.
<lang lua>local csv={}
<syntaxhighlight lang=lua>local csv={}
for line in io.lines('file.csv') do
for line in io.lines('file.csv') do
table.insert(csv, {})
table.insert(csv, {})
Line 2,845: Line 2,845:
local file=io.open('file.csv', 'w')
local file=io.open('file.csv', 'w')
file:write(newFileData)
file:write(newFileData)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,856: Line 2,856:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module Checkit {
Module Checkit {
Function Sum {
Function Sum {
Line 2,904: Line 2,904:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
Entire script:
Entire script:
<lang Maple>M := ImportMatrix("data.csv",source=csv);
<syntaxhighlight lang=Maple>M := ImportMatrix("data.csv",source=csv);
M(..,6) := < "Total", seq( add(M[i,j], j=1..5), i=2..5 ) >;
M(..,6) := < "Total", seq( add(M[i,j], j=1..5), i=2..5 ) >;
ExportMatrix("data_out.csv",M,target=csv);
ExportMatrix("data_out.csv",M,target=csv);
</syntaxhighlight>
</lang>


Running this script showing interactive results:
Running this script showing interactive results:
<lang Maple>> M := ImportMatrix("data.csv",source=csv);
<syntaxhighlight lang=Maple>> M := ImportMatrix("data.csv",source=csv);
["C1" "C2" "C3" "C4" "C5"]
["C1" "C2" "C3" "C4" "C5"]
[ ]
[ ]
Line 2,938: Line 2,938:
> ExportMatrix("data_out.csv",M,target=csv);
> ExportMatrix("data_out.csv",M,target=csv);
96
96
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica's Import and Export functions support CSV files.
Mathematica's Import and Export functions support CSV files.
<lang mathematica>iCSV=Import["test.csv"]
<syntaxhighlight lang=mathematica>iCSV=Import["test.csv"]
->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}}
->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}}
iCSV = Transpose@
iCSV = Transpose@
Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]];
Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]];
iCSV // MatrixForm
iCSV // MatrixForm
Export["test.csv",iCSV];</lang>
Export["test.csv",iCSV];</syntaxhighlight>
{{out}}
{{out}}
<pre>(C1 C2 C3 C4 C5 Sum
<pre>(C1 C2 C3 C4 C5 Sum
Line 2,959: Line 2,959:
=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
=== Using file manipulation ===
=== Using file manipulation ===
<lang Matlab>filename='data.csv';
<syntaxhighlight lang=Matlab>filename='data.csv';
fid = fopen(filename);
fid = fopen(filename);
header = fgetl(fid);
header = fgetl(fid);
Line 2,971: Line 2,971:
fprintf(fid,"%i\n",sum(X(k,:)));
fprintf(fid,"%i\n",sum(X(k,:)));
end;
end;
fclose(fid);</lang>
fclose(fid);</syntaxhighlight>


=== Using <code>table</code> ===
=== Using <code>table</code> ===
<lang Matlab>filename='data.csv';
<syntaxhighlight lang=Matlab>filename='data.csv';
data = readtable(filename);
data = readtable(filename);
data.SUM = sum([data{:,:}],2);
data.SUM = sum([data{:,:}],2);
writetable(data,filename);</lang>
writetable(data,filename);</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
Nanoquery was created to parse and manipulate data files, with CSV being the first targeted format. As a result, it has a number of operators for retrieving data from a CSV file, including the record operator '#', the column operator '@', and the lookup operator '~'
Nanoquery was created to parse and manipulate data files, with CSV being the first targeted format. As a result, it has a number of operators for retrieving data from a CSV file, including the record operator '#', the column operator '@', and the lookup operator '~'
<lang Nanoquery>def sum(record)
<syntaxhighlight lang=Nanoquery>def sum(record)
sum = 0
sum = 0
Line 2,998: Line 2,998:
end for
end for
write</lang>
write</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
Line 3,004: Line 3,004:
{{libheader|Apache commons-csv}}
{{libheader|Apache commons-csv}}
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols
options replace format comments java crossref symbols


Line 3,126: Line 3,126:
end
end
return lineOut
return lineOut
</syntaxhighlight>
</lang>
{{in}} data/csvtest_in.csv
{{in}} data/csvtest_in.csv
<pre>
<pre>
Line 3,148: Line 3,148:
Nim's standard library contains a robust CSV parser, but for this simple document that's not necessary.
Nim's standard library contains a robust CSV parser, but for this simple document that's not necessary.


<lang nim>import strutils, streams
<syntaxhighlight lang=nim>import strutils, streams


let
let
Line 3,172: Line 3,172:
outf.writeLine(line)
outf.writeLine(line)


inc lineNumber</lang>
inc lineNumber</syntaxhighlight>


{{out}}
{{out}}
Line 3,186: Line 3,186:
Objeck has a CSV parser with built-in functions.
Objeck has a CSV parser with built-in functions.


<lang objeck>use System.IO.File;
<syntaxhighlight lang=objeck>use System.IO.File;
use Data.CSV;
use Data.CSV;


Line 3,218: Line 3,218:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,234: Line 3,234:
Using the '''csv''' module available in '''Opam''':
Using the '''csv''' module available in '''Opam''':


<lang ocaml>let list_add_last this lst =
<syntaxhighlight lang=ocaml>let list_add_last this lst =
List.rev (this :: (List.rev lst))
List.rev (this :: (List.rev lst))


Line 3,252: Line 3,252:
) data
) data
in
in
Csv.output_all (Csv.to_channel stdout) (fields :: sums)</lang>
Csv.output_all (Csv.to_channel stdout) (fields :: sums)</syntaxhighlight>


{{out}}
{{out}}
Line 3,271: Line 3,271:
{{Works with|PARI/GP|2.7.4 and above}}
{{Works with|PARI/GP|2.7.4 and above}}


<lang parigp>
<syntaxhighlight lang=parigp>
\\ CSV data manipulation
\\ CSV data manipulation
\\ 10/24/16 aev
\\ 10/24/16 aev
Line 3,290: Line 3,290:
\\ Testing:
\\ Testing:
processCsv("c:\\pariData\\test");
processCsv("c:\\pariData\\test");
</syntaxhighlight>
</lang>


{{in}} data/test.csv file
{{in}} data/test.csv file
Line 3,311: Line 3,311:
{{works with|Free Pascal}}
{{works with|Free Pascal}}
In Pascal you can use TStringList CommaText property to work with CSV.
In Pascal you can use TStringList CommaText property to work with CSV.
<lang pascal>
<syntaxhighlight lang=pascal>
program CSV_Data_Manipulation;
program CSV_Data_Manipulation;
uses Classes, SysUtils;
uses Classes, SysUtils;
Line 3,357: Line 3,357:
ts.Free;
ts.Free;
end.
end.
</syntaxhighlight>
</lang>


{{in}} input.csv file
{{in}} input.csv file
Line 3,377: Line 3,377:
=={{header|Perl}}==
=={{header|Perl}}==
For simple files, you can use [http://p3rl.org/split split]:
For simple files, you can use [http://p3rl.org/split split]:
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang=perl>#!/usr/bin/perl
use warnings;
use warnings;
use strict;
use strict;
Line 3,415: Line 3,415:
print join(',' => @header), "\n";
print join(',' => @header), "\n";
print join(',' => @$_), "\n" for @rows;
print join(',' => @$_), "\n" for @rows;
</syntaxhighlight>
</lang>


However, if the CSV can contain quoted texts (the type MS Excel produces), you should rather use the [http://p3rl.org/Text::CSV Text::CSV]. Only reading the data and printing the result is different:
However, if the CSV can contain quoted texts (the type MS Excel produces), you should rather use the [http://p3rl.org/Text::CSV Text::CSV]. Only reading the data and printing the result is different:
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang=perl>#!/usr/bin/perl
use warnings;
use warnings;
use strict;
use strict;
Line 3,442: Line 3,442:


# Print the output.
# Print the output.
$csv->print(*STDOUT, $_) for \@header, @rows;</lang>
$csv->print(*STDOUT, $_) for \@header, @rows;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Note that error checking is omitted, in particular for scanf, and obviously we use an inline constant for pwa/p2js, but normal file i/o for desktop/Phix.
Note that error checking is omitted, in particular for scanf, and obviously we use an inline constant for pwa/p2js, but normal file i/o for desktop/Phix.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tcsv</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
<span style="color: #008080;">constant</span> <span style="color: #000000;">tcsv</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Line 3,476: Line 3,476:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,488: Line 3,488:
=={{header|PHP}}==
=={{header|PHP}}==


<lang PHP>
<syntaxhighlight lang=PHP>
<?php
<?php


Line 3,524: Line 3,524:
$row++;
$row++;
}
}
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(in "data.csv"
<syntaxhighlight lang=PicoLisp>(in "data.csv"
(prinl (line) "," "SUM")
(prinl (line) "," "SUM")
(while (split (line) ",")
(while (split (line) ",")
(prinl (glue "," @) "," (sum format @)) ) )</lang>
(prinl (glue "," @) "," (sum format @)) ) )</syntaxhighlight>
{{Out}}
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
<pre>C1,C2,C3,C4,C5,SUM
Line 3,539: Line 3,539:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>*process source xref attributes or(!);
<syntaxhighlight lang=pli>*process source xref attributes or(!);
csv: Proc Options(Main);
csv: Proc Options(Main);
/*********************************************************************
/*********************************************************************
Line 3,603: Line 3,603:
End;
End;


End;</lang>
End;</syntaxhighlight>
{{in}}
{{in}}
<pre>
<pre>
Line 3,622: Line 3,622:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>## Create a CSV file
<syntaxhighlight lang=PowerShell>## Create a CSV file
@"
@"
C1,C2,C3,C4,C5
C1,C2,C3,C4,C5
Line 3,655: Line 3,655:
## Display the object in tabular form
## Display the object in tabular form
$records | Format-Table -AutoSize
$records | Format-Table -AutoSize
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,671: Line 3,671:
The following uses SWI-Prolog's csv_read_file_row/3 in order to
The following uses SWI-Prolog's csv_read_file_row/3 in order to
demonstrate that it is not necessary to read more than a line at a time.
demonstrate that it is not necessary to read more than a line at a time.
<lang Prolog>test :- augment('test.csv', 'test.out.csv').
<syntaxhighlight lang=Prolog>test :- augment('test.csv', 'test.out.csv').


% augment( +InFileName, +OutFileName)
% augment( +InFileName, +OutFileName)
Line 3,693: Line 3,693:
append(List, [Sum], NewList),
append(List, [Sum], NewList),
NewTerm =.. [F | NewList].
NewTerm =.. [F | NewList].
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>
<syntaxhighlight lang=PureBasic>
EnableExplicit
EnableExplicit


Line 3,748: Line 3,748:
CloseConsole()
CloseConsole()
EndIf
EndIf
</syntaxhighlight>
</lang>


{{out|Output (in output.csv)}}
{{out|Output (in output.csv)}}
Line 3,763: Line 3,763:
=== Using <code>fileinput</code> ===
=== Using <code>fileinput</code> ===
Note that the [http://docs.python.org/3.3/library/csv.html csv module] is not required for such a simple and regular CSV file. Here overwriting is done in place.
Note that the [http://docs.python.org/3.3/library/csv.html csv module] is not required for such a simple and regular CSV file. Here overwriting is done in place.
<lang python>import fileinput
<syntaxhighlight lang=python>import fileinput


changerow, changecolumn, changevalue = 2, 4, '"Spam"'
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
Line 3,773: Line 3,773:
fields[changecolumn-1] = changevalue
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
line = ','.join(fields) + '\n'
print(line, end='')</lang>
print(line, end='')</syntaxhighlight>
{{out}}
{{out}}
After this the data file <code>csv_data_manipulation.csv</code> gets changed from that of the task to:
After this the data file <code>csv_data_manipulation.csv</code> gets changed from that of the task to:
Line 3,784: Line 3,784:
=== Using <code>csv</code>, <code>pathlib</code> and <code>tempfile</code> ===
=== Using <code>csv</code>, <code>pathlib</code> and <code>tempfile</code> ===
In this example overwriting is performed ''not'' in place but by using [https://docs.python.org/library/tempfile.html <code>tempfile</code> library] for creating a temporary file and [https://docs.python.org/library/pathlib.html <code>pathlib</code> library] for overwriting the initial file. [http://docs.python.org/library/csv.html <code>csv</code> module] is used to allow easier manipulation with delimiters.
In this example overwriting is performed ''not'' in place but by using [https://docs.python.org/library/tempfile.html <code>tempfile</code> library] for creating a temporary file and [https://docs.python.org/library/pathlib.html <code>pathlib</code> library] for overwriting the initial file. [http://docs.python.org/library/csv.html <code>csv</code> module] is used to allow easier manipulation with delimiters.
<lang python>import csv
<syntaxhighlight lang=python>import csv
from pathlib import Path
from pathlib import Path
from tempfile import NamedTemporaryFile
from tempfile import NamedTemporaryFile
Line 3,806: Line 3,806:
temp_file_path = Path(temp_file.name)
temp_file_path = Path(temp_file.name)
temp_file_path.replace(filepath)
temp_file_path.replace(filepath)
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
<pre>C1,C2,C3,C4,C5,SUM
Line 3,815: Line 3,815:


=== Using <code>pandas</code> ===
=== Using <code>pandas</code> ===
<lang python>import pandas as pd
<syntaxhighlight lang=python>import pandas as pd


filepath = 'data.csv'
filepath = 'data.csv'
Line 3,822: Line 3,822:
rows_sums = df.sum(axis=1)
rows_sums = df.sum(axis=1)
df['SUM'] = rows_sums
df['SUM'] = rows_sums
df.to_csv(filepath, index=False)</lang>
df.to_csv(filepath, index=False)</syntaxhighlight>


=={{header|Q}}==
=={{header|Q}}==
<lang q>t:("IIIII";enlist ",")0: `:input.csv / Read CSV file input.csv into table t
<syntaxhighlight lang=q>t:("IIIII";enlist ",")0: `:input.csv / Read CSV file input.csv into table t
t:update SUM:sum value flip t from t / Add SUM column to t
t:update SUM:sum value flip t from t / Add SUM column to t
`:output.csv 0: csv 0: t / Write updated table as CSV to output.csv</lang>
`:output.csv 0: csv 0: t / Write updated table as CSV to output.csv</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang rsplus>
<syntaxhighlight lang=rsplus>
df <- read.csv(textConnection(
df <- read.csv(textConnection(
"C1,C2,C3,C4,C5
"C1,C2,C3,C4,C5
Line 3,840: Line 3,840:
df$sum <- rowSums(df)
df$sum <- rowSums(df)
write.csv(df,row.names = FALSE)
write.csv(df,row.names = FALSE)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,852: Line 3,852:


This output can also be saved to a file:
This output can also be saved to a file:
<lang R> write.csv(df, file = "foo.csv",row.names = FALSE)
<syntaxhighlight lang=R> write.csv(df, file = "foo.csv",row.names = FALSE)
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang=racket>#lang racket
(require (planet neil/csv:1:=7) net/url)
(require (planet neil/csv:1:=7) net/url)


Line 3,872: Line 3,872:
(append row (list (~a (apply + xs))))))
(append row (list (~a (apply + xs))))))
(define (->string row) (string-join row "," #:after-last "\n"))
(define (->string row) (string-join row "," #:after-last "\n"))
(string-append* (map ->string (cons head rows))))</lang>
(string-append* (map ->string (cons head rows))))</syntaxhighlight>
Example:
Example:
<lang racket>(define csv-file
<syntaxhighlight lang=racket>(define csv-file
"C1, C2, C3, C4, C5
"C1, C2, C3, C4, C5
1, 5, 9, 13, 17
1, 5, 9, 13, 17
Line 3,881: Line 3,881:
4, 8, 12, 16, 20")
4, 8, 12, 16, 20")


(display (all-rows (open-input-string csv-file)))</lang>
(display (all-rows (open-input-string csv-file)))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,894: Line 3,894:
(formerly Perl 6)
(formerly Perl 6)
On the face of it this task is pretty simple. Especially given the sample CSV file and the total lack of specification of ''what'' changes to make to the file. Something like this would suffice.
On the face of it this task is pretty simple. Especially given the sample CSV file and the total lack of specification of ''what'' changes to make to the file. Something like this would suffice.
<lang perl6>my $csvfile = './whatever.csv';
<syntaxhighlight lang=raku line>my $csvfile = './whatever.csv';
my $fh = open($csvfile, :r);
my $fh = open($csvfile, :r);
my @header = $fh.get.split(',');
my @header = $fh.get.split(',');
Line 3,903: Line 3,903:
$out.say((@header,'SUM').join(','));
$out.say((@header,'SUM').join(','));
$out.say((@$_, [+] @$_).join(',')) for @csv;
$out.say((@$_, [+] @$_).join(',')) for @csv;
close $out;</lang>
close $out;</syntaxhighlight>
But if your CSV file is at all complex you are better off using a CSV parsing module. (Complex meaning fields that contain commas, quotes, newlines, etc.)
But if your CSV file is at all complex you are better off using a CSV parsing module. (Complex meaning fields that contain commas, quotes, newlines, etc.)
<lang perl6>use Text::CSV;
<syntaxhighlight lang=raku line>use Text::CSV;
my $csvfile = './whatever.csv';
my $csvfile = './whatever.csv';
my @csv = Text::CSV.parse-file($csvfile);
my @csv = Text::CSV.parse-file($csvfile);
# modify(@csv); # do whatever;
# modify(@csv); # do whatever;
csv-write-file( @csv, :file($csvfile) );</lang>
csv-write-file( @csv, :file($csvfile) );</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>>>filein: read/lines %file.csv
<syntaxhighlight lang=Red>>>filein: read/lines %file.csv
>>data: copy []
>>data: copy []
>>foreach item filein [append/only data split item ","]
>>foreach item filein [append/only data split item ","]
; [["C1" "C2" "C3" "C4" "C5"] ["1" "5" "9" "13" "17"] ["2" "6" "10" "14" "18"] ["3" "7" "11" "15" "19"]["4" "8" "12" "16" "20"]]</lang>
; [["C1" "C2" "C3" "C4" "C5"] ["1" "5" "9" "13" "17"] ["2" "6" "10" "14" "18"] ["3" "7" "11" "15" "19"]["4" "8" "12" "16" "20"]]</syntaxhighlight>


<lang Red>>>forall data [either (index? data) = 1[
<syntaxhighlight lang=Red>>>forall data [either (index? data) = 1[
append data/1 "SUM"
append data/1 "SUM"
][
][
append data/1 to string!
append data/1 to string!
(to integer! data/1/1) + (to integer! data/1/2) + (to integer! data/1/3) + (to integer! data/1/4) + (to integer! data/1/5)
(to integer! data/1/1) + (to integer! data/1/2) + (to integer! data/1/3) + (to integer! data/1/4) + (to integer! data/1/5)
]]</lang>
]]</syntaxhighlight>
<lang Red>>>foreach item data [append item/6 "^/" repeat c 5 [append item/:c ","]]
<syntaxhighlight lang=Red>>>foreach item data [append item/6 "^/" repeat c 5 [append item/:c ","]]
>> print data
>> print data
C1, C2, C3, C4, C5, SUM
C1, C2, C3, C4, C5, SUM
Line 3,930: Line 3,930:
3, 7, 11, 15, 19, 55
3, 7, 11, 15, 19, 55
4, 8, 12, 16, 20, 60
4, 8, 12, 16, 20, 60
>>write fileout.csv form data</lang>
>>write fileout.csv form data</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang=rexx>/* REXX ***************************************************************
* extend in.csv to add a column containing the sum of the lines' elems
* extend in.csv to add a column containing the sum of the lines' elems
* 21.06.2013 Walter Pachl
* 21.06.2013 Walter Pachl
Line 3,957: Line 3,957:
Do i=1 To i-1
Do i=1 To i-1
Call lineout csv,l.i
Call lineout csv,l.i
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
<pre>C1,C2,C3,C4,C5,SUM
Line 3,970: Line 3,970:


Also supported is the ability to specify the fileID of the data file to be specified.
Also supported is the ability to specify the fileID of the data file to be specified.
<lang rexx>/*REXX program reads a CSV file & appends a SUM column (which is the sum of all columns)*/
<syntaxhighlight lang=rexx>/*REXX program reads a CSV file & appends a SUM column (which is the sum of all columns)*/
parse arg iFID . /*obtain optional argument from the CL*/
parse arg iFID . /*obtain optional argument from the CL*/
if iFID=='' | iFID=="," then iFID= 'CSV_SUM.DAT' /*Not specified? Then use the default*/
if iFID=='' | iFID=="," then iFID= 'CSV_SUM.DAT' /*Not specified? Then use the default*/
Line 3,988: Line 3,988:
do k=2 for rec-2 /*process all the records just read. */
do k=2 for rec-2 /*process all the records just read. */
call lineout iFID,@.k /*write the new CSV record (has SUM). */
call lineout iFID,@.k /*write the new CSV record (has SUM). */
end /*k*/ /*stick a fork in it, we're all done.*/</lang>
end /*k*/ /*stick a fork in it, we're all done.*/</syntaxhighlight>
{{out|output|text=&nbsp; to the console:}}
{{out|output|text=&nbsp; to the console:}}
<pre>
<pre>
Line 3,996: Line 3,996:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
# Project : CSV data manipulation
# Project : CSV data manipulation


Line 4,031: Line 4,031:
fclose(fpout)
fclose(fpout)
see csvend + nl
see csvend + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 4,042: Line 4,042:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require 'csv'
<syntaxhighlight lang=ruby>require 'csv'
# read:
# read:
ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible.
ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible.
Line 4,053: Line 4,053:
CSV.open("out.csv", 'w') do |csv|
CSV.open("out.csv", 'w') do |csv|
ar.each{|line| csv << line}
ar.each{|line| csv << line}
end</lang>
end</syntaxhighlight>
{{output}}
{{output}}
<pre>c1,c2,c3,c4,c5,SUM
<pre>c1,c2,c3,c4,c5,SUM
Line 4,062: Line 4,062:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>csv$ = "C1,C2,C3,C4,C5
<syntaxhighlight lang=runbasic>csv$ = "C1,C2,C3,C4,C5
1,5,9,13,17
1,5,9,13,17
2,6,10,14,18
2,6,10,14,18
Line 4,095: Line 4,095:
cma$ = ""
cma$ = ""
print
print
next r</lang>
next r</syntaxhighlight>
<pre>C1,C2,C3,C4,C5
<pre>C1,C2,C3,C4,C5
1,5,9,13,17
1,5,9,13,17
Line 4,113: Line 4,113:
=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|BurntSushi's csv crate}}
{{libheader|BurntSushi's csv crate}}
<lang rust>use std::error::Error;
<syntaxhighlight lang=rust>use std::error::Error;
use std::num::ParseIntError;
use std::num::ParseIntError;
use csv::{Reader, Writer};
use csv::{Reader, Writer};
Line 4,140: Line 4,140:
writer.flush()?;
writer.flush()?;
Ok(())
Ok(())
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>C1,C2,C3,C4,C5,SUM
<pre>C1,C2,C3,C4,C5,SUM
Line 4,149: Line 4,149:


=={{header|SAS}}==
=={{header|SAS}}==
<lang sas>data _null_;
<syntaxhighlight lang=sas>data _null_;
infile datalines dlm="," firstobs=2;
infile datalines dlm="," firstobs=2;
file "output.csv" dlm=",";
file "output.csv" dlm=",";
Line 4,163: Line 4,163:
4,8,12,16,20
4,8,12,16,20
;
;
run;</lang>
run;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang Scala>import scala.io.Source
<syntaxhighlight lang=Scala>import scala.io.Source


object parseCSV extends App {
object parseCSV extends App {
Line 4,194: Line 4,194:


*/
*/
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 4,200: Line 4,200:
is in the same directory as the program.
is in the same directory as the program.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 4,216: Line 4,216:
writeln(join(csvData[line], ","));
writeln(join(csvData[line], ","));
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,228: Line 4,228:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang=sensetalk>
// For test purposes, start by creating (or re-creating) the data file
// For test purposes, start by creating (or re-creating) the data file
put {{
put {{
Line 4,254: Line 4,254:
put file "myData.csv" -- display the updated file contents
put file "myData.csv" -- display the updated file contents


</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
For simple files we can use the ''split'' method.
For simple files we can use the ''split'' method.
<lang ruby># Read
<syntaxhighlight lang=ruby># Read
var csvfile = %f'data.csv';
var csvfile = %f'data.csv';
var fh = csvfile.open_r;
var fh = csvfile.open_r;
Line 4,270: Line 4,270:
out.say([header..., 'SUM'].join(','));
out.say([header..., 'SUM'].join(','));
csv.each { |row| out.say([row..., row.sum].join(',')) };
csv.each { |row| out.say([row..., row.sum].join(',')) };
out.close;</lang>
out.close;</syntaxhighlight>


For complex files, the ''Text::CSV'' library is recommended.
For complex files, the ''Text::CSV'' library is recommended.
<lang ruby>var csv = require('Text::CSV').new(
<syntaxhighlight lang=ruby>var csv = require('Text::CSV').new(
Hash(eol => "\n")
Hash(eol => "\n")
);
);
Line 4,296: Line 4,296:
[header, rows...].each { |row|
[header, rows...].each { |row|
csv.print(out, row);
csv.print(out, row);
};</lang>
};</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>import delim input.csv, clear
<syntaxhighlight lang=stata>import delim input.csv, clear
replace c5=c3+c4
replace c5=c3+c4
egen sum=rowtotal(c*)
egen sum=rowtotal(c*)
drop if mod(c3,3)==0
drop if mod(c3,3)==0
export delim output.csv, replace</lang>
export delim output.csv, replace</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|struct::matrix}}
{{tcllib|struct::matrix}}
{{tcllib|csv}}
{{tcllib|csv}}
<lang tcl>package require struct::matrix
<syntaxhighlight lang=tcl>package require struct::matrix
package require csv
package require csv


Line 4,336: Line 4,336:
}
}


addSumColumn "example.csv"</lang>
addSumColumn "example.csv"</syntaxhighlight>
{{out|Output (in <tt>example.csv</tt>)}}
{{out|Output (in <tt>example.csv</tt>)}}
<pre>
<pre>
Line 4,347: Line 4,347:


Although, for this specific small task,
Although, for this specific small task,
<lang tcl>set f [open example.csv r]
<syntaxhighlight lang=tcl>set f [open example.csv r]
puts "[gets $f],SUM"
puts "[gets $f],SUM"
while { [gets $f row] > 0 } {
while { [gets $f row] > 0 } {
puts "$row,[expr [string map {, +} $row]]"
puts "$row,[expr [string map {, +} $row]]"
}
}
close $f</lang>
close $f</syntaxhighlight>
suffices.
suffices.


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang=tuscript>
$$ MODE DATA
$$ MODE DATA
$$ csv=*
$$ csv=*
Line 4,375: Line 4,375:
csv=APPEND(csv,line)
csv=APPEND(csv,line)
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,386: Line 4,386:


=={{header|TXR}}==
=={{header|TXR}}==
<lang txr>@(coll)@{name /[^,]+/}@(end)
<syntaxhighlight lang=txr>@(coll)@{name /[^,]+/}@(end)
@(collect :vars (value sum))
@(collect :vars (value sum))
@ (bind sum 0)
@ (bind sum 0)
Line 4,397: Line 4,397:
@ (end)
@ (end)
@(end)
@(end)
</syntaxhighlight>
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 4,403: Line 4,403:


Very simple solution using powerfull and ancient but strong linux command, I named "tr" and "bc", and internal variable bash test capabilities :
Very simple solution using powerfull and ancient but strong linux command, I named "tr" and "bc", and internal variable bash test capabilities :
<lang>cat csv | while read S; do
<syntaxhighlight lang=text>cat csv | while read S; do
[ -z ${S##*C*} ] && echo $S,SUM || echo $S,`echo $S | tr ',' '+' | bc`
[ -z ${S##*C*} ] && echo $S,SUM || echo $S,`echo $S | tr ',' '+' | bc`
done</lang>
done</syntaxhighlight>


Result :
Result :
<lang>C1,C2,C3,C4,C5,SUM
<syntaxhighlight lang=text>C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
1,5,9,13,17,45
2,6,10,14,18,50
2,6,10,14,18,50
3,7,11,15,19,55
3,7,11,15,19,55
4,8,12,16,20,60</lang>
4,8,12,16,20,60</syntaxhighlight>


Other solution (not from me) :
Other solution (not from me) :


<lang>bash>exec 0<"$1" # open the input file on stdin
<syntaxhighlight lang=text>bash>exec 0<"$1" # open the input file on stdin
exec 1>"$1.new" # open an output file on stdout
exec 1>"$1.new" # open an output file on stdout
{
{
Line 4,435: Line 4,435:
} &&
} &&
mv "$1" "$1.bak" &&
mv "$1" "$1.bak" &&
mv "$1.new" "$1"</lang>
mv "$1.new" "$1"</syntaxhighlight>


{{works with|ksh}}
{{works with|ksh}}
Line 4,446: Line 4,446:
{{works with|R3}}
{{works with|R3}}
uBasic/4tH can read text files and has a built-in tokenizer, so parsing simple CSV files is not a problem.
uBasic/4tH can read text files and has a built-in tokenizer, so parsing simple CSV files is not a problem.
<lang>if set (a, open ("yourcsv.csv", "r")) < 0 then
<syntaxhighlight lang=text>if set (a, open ("yourcsv.csv", "r")) < 0 then
print "Cannot open \qyourcsv.csv\q" ' open file a for reading
print "Cannot open \qyourcsv.csv\q" ' open file a for reading
end ' abort on file opening errors
end ' abort on file opening errors
Line 4,481: Line 4,481:


close a : close b : end ' close files and terminate
close a : close b : end ' close files and terminate
</syntaxhighlight>
</lang>
=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>#
<syntaxhighlight lang=ursa>#
# csv data manipulation
# csv data manipulation
#
#
Line 4,524: Line 4,524:
for (set i 0) (< i (size lines)) (inc i)
for (set i 0) (< i (size lines)) (inc i)
out lines<i> endl f
out lines<i> endl f
end for</lang>
end for</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
Using Excel VBA to load a CSV file in a new workbook.
Using Excel VBA to load a CSV file in a new workbook.


<lang vb>Sub ReadCSV()
<syntaxhighlight lang=vb>Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F1").Value = "Sum"
Line 4,535: Line 4,535:
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
ActiveWindow.Close
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>'Instatiate FSO.
<syntaxhighlight lang=vb>'Instatiate FSO.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv.
'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv.
Line 4,572: Line 4,572:
AddElements = AddElements + CInt(arr(i))
AddElements = AddElements + CInt(arr(i))
Next
Next
End Function</lang>
End Function</syntaxhighlight>


{{In}}
{{In}}
Line 4,592: Line 4,592:
=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
This example adds 100 to the values in each cell at row n+1, column n.
This example adds 100 to the values in each cell at row n+1, column n.
<lang vedit>File_Open("input.csv")
<syntaxhighlight lang=vedit>File_Open("input.csv")
for (#1 = 0; #1 < 4; #1++) {
for (#1 = 0; #1 < 4; #1++) {
Goto_Line(#1+2) // line (starting from line 2)
Goto_Line(#1+2) // line (starting from line 2)
Line 4,602: Line 4,602:
Num_Ins(#2+100, LEFT+NOCR) // write new value
Num_Ins(#2+100, LEFT+NOCR) // write new value
}
}
File_Save_As("output.csv", OK+NOMSG) </lang>
File_Save_As("output.csv", OK+NOMSG) </syntaxhighlight>
output.csv:
output.csv:
<pre>
<pre>
Line 4,613: Line 4,613:


=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
<lang vfp>
<syntaxhighlight lang=vfp>
CLOSE DATABASES ALL
CLOSE DATABASES ALL
SET SAFETY OFF
SET SAFETY OFF
Line 4,625: Line 4,625:
MODIFY FILE file2.csv NOEDIT IN SCREEN
MODIFY FILE file2.csv NOEDIT IN SCREEN
SET SAFETY ON
SET SAFETY ON
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
Wren does not have any built-in functions for dealing with generic CSV files so we therefore need to work from first principles.
Wren does not have any built-in functions for dealing with generic CSV files so we therefore need to work from first principles.
<lang ecmascript>import "io" for File
<syntaxhighlight lang=ecmascript>import "io" for File


var lines = File.read("rc.csv").split("\n").map { |w| w.trim() }.toList
var lines = File.read("rc.csv").split("\n").map { |w| w.trim() }.toList
Line 4,642: Line 4,642:
}
}
}
}
file.close()</lang>
file.close()</syntaxhighlight>


{{out}}
{{out}}
Line 4,659: Line 4,659:
and returns its text and integer values. The task's csv file is read and
and returns its text and integer values. The task's csv file is read and
written from a command line like this: csv <csv.txt >csv2.txt
written from a command line like this: csv <csv.txt >csv2.txt
<lang XPL0>string 0; \use zero-terminated strings
<syntaxhighlight lang=XPL0>string 0; \use zero-terminated strings
def LF=$0A, EOF=$1A;
def LF=$0A, EOF=$1A;
int Val, Char;
int Val, Char;
Line 4,698: Line 4,698:
CrLf(0);
CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,711: Line 4,711:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang yabasic>open #1, "manipy.csv", "r" //existing CSV file separated by spaces, not commas
<syntaxhighlight lang=yabasic>open #1, "manipy.csv", "r" //existing CSV file separated by spaces, not commas
open #2, "manip2.csv", "w" //new CSV file for writing changed data
open #2, "manip2.csv", "w" //new CSV file for writing changed data


Line 4,726: Line 4,726:
close #1
close #1
close #2
close #2
end</lang>
end</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>csvFile:=File("test.csv");
<syntaxhighlight lang=zkl>csvFile:=File("test.csv");
header:=csvFile.readln().strip(); // remove trailing "\n" and leading white space
header:=csvFile.readln().strip(); // remove trailing "\n" and leading white space
listOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(",").apply("toInt") });
listOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(",").apply("toInt") });
Line 4,736: Line 4,736:
newFile.writeln(header + ",sum");
newFile.writeln(header + ",sum");
listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(","),",",ns.sum()) });
listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(","),",",ns.sum()) });
newFile.close();</lang>
newFile.close();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>