Jump to content

CSV data manipulation: Difference between revisions

m (→‎{{header|Sidef}}: Fix link: Perl 6 --> Raku)
 
(39 intermediate revisions by 25 users not shown)
Line 27:
 
=={{header|11l}}==
<langsyntaxhighlight lang=11l>L(=line) File(‘data.csv’).read_lines()
I L.index == 0
line ‘’= ‘,SUM’
E
line ‘’= ‘,’sum(line.split(‘,’).map(i -> Int(i)))
print(line)</langsyntaxhighlight>
 
{{out}}
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):
 
<langsyntaxhighlight lang=Ada>package CSV is
type Row(<>) is tagged private;
Line 65:
Sep: Character;
end record;
end CSV;</langsyntaxhighlight>
 
The implementation of the package is
 
<langsyntaxhighlight lang=Ada>package body CSV is
function Line(S: String; Separator: Character := ',')
Line 92:
end Next;
end CSV;</langsyntaxhighlight>
 
Finally, the main program which uses the package CSV:
 
<langsyntaxhighlight lang=Ada>with CSV, Ada.Text_IO; use Ada.Text_IO;
 
procedure CSV_Data_Manipulation is
Line 114:
end;
end loop;
end CSV_Data_Manipulation;</langsyntaxhighlight>
 
{{out}}
Line 126:
 
=={{header|Aime}}==
<langsyntaxhighlight lang=aime>void
read_csv(list t, text path)
{
Line 198:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 207:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang=algol68># count occurrances of a char in string #
PROC char count = (CHAR c, STRING str) INT:
BEGIN
Line 294:
print ((join (fields, ","), new line))
OD;
close (foo)</langsyntaxhighlight>
{{out}}
<pre>
Line 303:
4,8,12,16,20,60
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang=rebol>; data.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
 
table: read.csv "data.csv"
data: []
loop table 'row [
addable: ["SUM"]
if row <> first table ->
addable: @[to :string sum map row 'x [to :integer x]]
'data ++ @[row ++ addable]
]
 
loop data 'row [
loop row 'column ->
prints pad column 6
print ""
]</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>Loop, Read, Data.csv
{
i := A_Index
Line 311 ⟶ 337:
Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? "`n" : ",")
}
FileAppend, %Output%, NewData.csv</langsyntaxhighlight>
'''Output:'''
<pre>C1,C2,C3,C4,C5
Line 321 ⟶ 347:
=={{header|AWK}}==
adds a column sum to a csv table
<langsyntaxhighlight lang=AWK>#!/usr/bin/awk -f
BEGIN { FS = OFS = "," }
NR==1 {
Line 333 ⟶ 359:
}
print $0, sum
}</langsyntaxhighlight>
<pre>awk -f csv_data_manipulation.awk data.csv
C1,C2,C3,C4,C5,SUM
Line 340 ⟶ 366:
3,7,11,15,19,55
4,8,12,16,20,60</pre>
 
=={{header|BaCon}}==
Load the data, change a value and add a column with totals. Then save and print.
<syntaxhighlight lang=BaCon>OPTION COLLAPSE TRUE
OPTION DELIM ","
 
csv$ = LOAD$("data.csv")
 
DOTIMES AMOUNT(csv$, NL$)
line$ = TOKEN$(csv$, _, NL$)
 
IF _ = 1 THEN
total$ = APPEND$(line$, 0, "SUM")
ELSE
line$ = CHANGE$(line$, _, STR$(_*10) )
total$ = APPEND$(total$, 0, line$, NL$)
total$ = APPEND$(total$, 0, STR$(LOOP(i, AMOUNT(line$), VAL(TOKEN$(line$, i)))) )
FI
DONE
 
SAVE total$ TO "data.csv"
PRINT total$
</syntaxhighlight>
<pre>
C1,C2,C3,C4,C5,SUM
1,20,9,13,17,60
2,6,30,14,18,70
3,7,11,40,19,80
4,8,12,16,50,90
</pre>
 
 
 
=={{header|BASIC}}==
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
<syntaxhighlight lang=qbasic>OPEN "manip.csv" FOR INPUT AS #1
OPEN "manip2.csv" FOR OUTPUT AS #2
 
LINE INPUT #1, header$
PRINT #2, header$ + ",SUM"
 
WHILE NOT EOF(1)
INPUT #1, c1, c2, c3, c4, c5
sum = c1 + c2 + c3 + c4 + c5
WRITE #2, c1, c2, c3, c4, c5, sum
WEND
 
CLOSE #1, #2
END</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
=={{header|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"⟩
 
Split ← (⊢-˜¬×+`)∘=⟜','⊸⊔
strdata ← >Split¨csvstr
intdata ← •BQN¨⌾(1⊸↓) strdata
sums ← ⟨"SUMS"⟩ ∾+´˘ 1↓ intdata
done ← sums ∾˜˘ intdata
</syntaxhighlight>
 
=={{header|C}}==
<syntaxhighlight lang=c>
<lang c>
 
#define TITLE "CSV data manipulation"
Line 619 ⟶ 712:
return 0;
}
</syntaxhighlight>
</lang>
{{out|Output (in <tt>tmp/csv-data-manipulation.result.csv</tt>)}}
<pre>
Line 629 ⟶ 722:
</pre>
 
==={{headerlibheader|C sharpGadget}}===
<syntaxhighlight lang="c">
<lang csharp>using System.IO;
#include <gadget/gadget.h>
 
LIB_GADGET_START
 
void Muestra_archivo_original();
 
Main
if(Exist_file("load_matrix.txt"))
{
/* recupero informacion del archivo para su apertura segura */
F_STAT dataFile = Stat_file("load_matrix.txt");
if(dataFile.is_matrix) // tiene forma de matriz???
{
New multitype test;
/* establezco los rangos a leer */
Range for test [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];
/* cargamos el array con detección de enteros como LONG */
test = Load_matrix_mt( pSDS(test), "load_matrix.txt", dataFile, DET_LONG);
/* modifica algunas cosas del archivo */
/* sChg() no es necesario aquí, porque no se está cambiando el tipo
de la celda, sino que se reemplaza el string: */
///sChg( test, 0,1, "Columna 1");
 
/* Con Let() basta... */
Let( $s-test[0,1], "Columna 1");
$l-test[2,1] = 1000;
$l-test[2,2] = 2000;
/* inserto filas */
/* preparo la fila a insertar */
New multitype nueva_fila;
sAppend_mt(nueva_fila,"fila 3.1");
Append_mt(nueva_fila,float,0.0);
Append_mt(nueva_fila,int,0);
Append_mt(nueva_fila,double,0.0);
Append_mt(nueva_fila,long, 0L);
/* insertamos la misma fila en el array, 3 veces */
test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);
test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);
test = Insert_row_mt(pSDS(test),pSDS(nueva_fila), 4);
Free multitype nueva_fila;
Print "\nGuardando archivo en \"save_matrix.txt\"...\n";
DEC_PREC = 20; /* establece precision decimal para despliegue */
All range for test;
Save_matrix_mt(SDS(test), "save_matrix.txt" );
 
Free multitype test;
Print "\nArchivo original:\n";
Muestra_archivo_original();
}
}
 
End
 
void Muestra_archivo_original(){
String csys;
csys = `cat load_matrix.txt`;
Print "\n%s\n", csys;
Free secure csys;
}
</syntaxhighlight>
{{out}}
<pre>
$ ./tests/loadmt
 
Guardando archivo en "save_matrix.txt"...
 
Archivo original:
 
+,head 1,head 2,head 3,head 4
fila 1,0.7226562500000,0.7198443412781,0.7170542478561,0.7142857313156
fila 2,83,77,93,86
fila 3,0.5000000000000,0.5150380749101,0.5299192642332,0.5446390350150
fila 4,30886,36915,38335,60492
fila 5,1.8213465987073e+2,1.8213465987073e+4,1.8213465987073e+6,1.8213465987073e+8
fila 6,1.8213465987073e-2,1.8213465987073e-4,1.8213465987073e-6,1.8213465987073e-8
 
$ cat save_matrix.txt
+,Columna 1,head 2,head 3,head 4
fila 1,0.72265625000000000000,0.71984434127810004167,0.71705424785609994665,0.71428573131560002540
fila 2,1000,2000,93,86
fila 3,0.50000000000000000000,0.51503807491010000774,0.52991926423320001582,0.54463903501499999482
fila 3.1,0.00000000000000000000,0,0.00000000000000000000,0
fila 3.1,0.00000000000000000000,0,0.00000000000000000000,0
fila 3.1,0.00000000000000000000,0,0.00000000000000000000,0
fila 4,30886,36915,38335,60492
fila 5,182.13465987073001883800,18213.46598707299926900305,1821346.59870730014517903328,182134659.87073001265525817871
fila 6,0.01821346598707300132,0.00018213465987073003,0.00000182134659870730,0.00000001821346598707
$
</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>using System.IO;
using System.Linq;
 
Line 651 ⟶ 843:
}
}
</syntaxhighlight>
</lang>
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 662 ⟶ 854:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>#include <map>
#include <vector>
#include <iostream>
Line 790 ⟶ 982:
oCSV.save( "test_out.csv" );
return 0;
}</langsyntaxhighlight>
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 801 ⟶ 993:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=clojure>
(require '[clojure.data.csv :as csv]
'[clojure.java.io :as io])
Line 816 ⟶ 1,008:
(with-open [out-file (io/writer "test_out.csv")]
(csv/write-csv out-file out-data)))))
</syntaxhighlight>
</lang>
 
{{out|Output (in <code>test_out.csv</code>)}}
Line 826 ⟶ 1,018:
4,8,12,16,20,60
</pre>
 
 
Using tech.ml.dataset
 
<syntaxhighlight lang=clojure>
(require '[tech.v3.dataset :as ds]
'[tech.v3.datatype.functional :as dfn])
 
(defn add-sum
[dataframe]
(assoc dataframe
"SUM"
(apply dfn/+ (map dataframe (ds/column-names dataframe)))))
 
(ds/write! (add-sum (ds/->dataset "resources/input.csv")) "resources/output.csv")
</syntaxhighlight>
 
=={{header|COBOL}}==
<syntaxhighlight lang=COBOL>
IDENTIFICATION DIVISION.
PROGRAM-ID. CSV.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 19 December 2021.
************************************************************
** Program Abstract:
** CSVs are something COBOL does pretty well.
** The commented out CONCATENATE statements are a
** second method other than the STRING method.
************************************************************
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
 
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT CSV-File ASSIGN TO "csv.txt"
ORGANIZATION IS LINE SEQUENTIAL.
SELECT Out-File ASSIGN TO "new.csv.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD CSV-File
DATA RECORD IS CSV-Record.
01 CSV-Record.
05 Field1 PIC X(64).
FD Out-File
DATA RECORD IS Out-Line.
01 Out-Line PIC X(80).
WORKING-STORAGE SECTION.
01 Eof PIC X VALUE 'F'.
01 CSV-Data.
05 CSV-Col1 PIC 9(5).
05 CSV-Col2 PIC 9(5).
05 CSV-Col3 PIC 9(5).
05 CSV-Col4 PIC 9(5).
05 CSV-Col5 PIC 9(5).
 
01 CSV-Sum PIC ZZZ9.
01 CSV-Sum-Alpha
REDEFINES CSV-Sum PIC X(4).
PROCEDURE DIVISION.
Main-Program.
OPEN INPUT CSV-File
OPEN OUTPUT Out-File
PERFORM Read-a-Record
PERFORM Build-Header
PERFORM UNTIL Eof = 'T'
PERFORM Read-a-Record
IF Eof NOT EQUAL 'T' PERFORM Process-a-Record
END-PERFORM
CLOSE CSV-File
CLOSE Out-File
STOP RUN.
Read-a-Record.
READ CSV-File
AT END MOVE 'T' TO Eof
END-READ.
 
Build-Header.
** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM"
** TO Out-Line.
STRING TRIM(CSV-Record), ",SUM" INTO Out-Line.
WRITE Out-Line.
MOVE SPACES TO Out-Line.
 
Process-a-Record.
UNSTRING CSV-Record DELIMITED BY ',' INTO
CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5.
COMPUTE CSV-Sum =
CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5.
** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha))
** TO Out-Line.
STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)
INTO Out-Line.
WRITE Out-Line.
MOVE SPACES TO Out-Line.
END-PROGRAM.
</syntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang=lisp>
(defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
Line 870 ⟶ 1,175:
result-header (nested-list-to-csv data-list ",")))))
(main)
</syntaxhighlight>
</lang>
 
{{out|Output (in <code>results.txt</code>)}}
Line 882 ⟶ 1,187:
 
=={{header|D}}==
<langsyntaxhighlight lang=d>void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
Line 891 ⟶ 1,196:
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}</langsyntaxhighlight>
{{out|Output (in <code>csv_data_out.csv</code>)}}
<pre>C1,C2,C3,C4,C5
Line 898 ⟶ 1,203:
4,8,12,16,20
5,9,13,17,21</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IoUtils}}
{{libheader| System.Types}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi>
program CSV_data_manipulation;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.IoUtils,
System.Types;
 
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
 
{ TStringDynArrayHelper }
 
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
 
const
FILENAME = './Data.csv';
 
var
i: integer;
Input, Row: TStringDynArray;
 
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.</syntaxhighlight>
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
4,8,12,16,20,60</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
s$ = input
print s$ & ",SUM"
repeat
s$ = input
until s$ = ""
sum = 0
for v in number strsplit s$ ","
sum += v
.
print s$ & "," & sum
.
input_data
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>
{{out}}
<pre>
C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
4,8,12,16,20,60
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang=scheme>
;; CSV -> LISTS
(define (csv->row line) (map (lambda(x) (or (string->number x) x)) (string-split line ",")))
Line 922 ⟶ 1,313:
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang=scheme>
(define file.csv #<<
C1,C2,C3,C4,C5
Line 940 ⟶ 1,331:
3,7,11,15,19,55
4,8,12,16,20,60"
</syntaxhighlight>
</lang>
 
=={{header|ECL}}==
<syntaxhighlight lang=text>// Assumes a CSV file exists and has been sprayed to a Thor cluster
MyFileLayout := RECORD
STRING Field1;
Line 963 ⟶ 1,354:
 
MyNewDataset := PROJECT(MyDataset,Appended(LEFT));
OUTPUT(myNewDataset,,'~Rosetta::myNewCSVFile',CSV,OVERWRITE);</langsyntaxhighlight>
{{Out}} (contents of Rosetta::myNewCSVFile):
<pre>C1x,C2y,C3z,C4a,C5b
Line 972 ⟶ 1,363:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang=Elixir>
defmodule Csv do
defstruct header: "", data: "", separator: ","
Line 1,024 ⟶ 1,415:
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,036 ⟶ 1,427:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang=Erlang>
-module( csv_data ).
 
Line 1,073 ⟶ 1,464:
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,085 ⟶ 1,476:
</pre>
 
=={{header|Euphoria|}}==
<langsyntaxhighlight lang=euphoria>--- Read CSV file and add columns headed with 'SUM'
--- with trace
-- trace(0)
Line 1,177 ⟶ 1,568:
 
main()
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,190 ⟶ 1,581:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang=fsharp>open System.IO
 
[<EntryPoint>]
Line 1,204 ⟶ 1,595:
File.WriteAllLines ("test_out.csv", output)
0
</syntaxhighlight>
</lang>
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 1,216 ⟶ 1,607:
=={{header|Factor}}==
The <code>csv</code> vocabulary provides words for working with csv files, strings, and streams.
<langsyntaxhighlight lang=factor>USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
 
Line 1,225 ⟶ 1,616:
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
 
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi</langsyntaxhighlight>
{{out}}
Contents of <code>example.csv</code>
Line 1,237 ⟶ 1,628:
 
=={{header|Forth}}==
<langsyntaxhighlight lang=forth>\ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues
\ USAGE:
\ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv
Line 1,285 ⟶ 1,676:
THEN
2DROP 2DROP
;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,298 ⟶ 1,689:
It's fairly easy to read arbitrary lines using allocatable character strings, available since Fortran 2003.
 
<langsyntaxhighlight lang=fortran>program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
Line 1,404 ⟶ 1,795:
array(p) = line(k:n)
end subroutine
end program</langsyntaxhighlight>
 
=== Old Fortran ===
Line 1,417 ⟶ 1,808:
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.
 
<langsyntaxhighlight lang=Fortran>
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"
Line 1,438 ⟶ 1,829:
10 CLOSE (IN) !All done.
END !That's all.
</syntaxhighlight>
</lang>
Output could of course be written to a disc file instead of a screen, but here it is:
<pre>
Line 1,449 ⟶ 1,840:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>' FB 1.05.0 Win64
 
Open "manip.csv" For Input As #1 ' existing CSV file
Line 1,468 ⟶ 1,859:
 
Close #1
Close #2</langsyntaxhighlight>
 
{{out}}
Line 1,482 ⟶ 1,873:
 
=={{header|FunL}}==
<langsyntaxhighlight lang=funl>import io.{lines, PrintWriter}
 
data Table( header, rows )
Line 1,526 ⟶ 1,917:
t = addColumn( read('test.csv'), 'SUM', r -> r('SUM') = sum(int(v) | (_, v) <- r if v != null) )
write( t, 'test_out.csv' )
write( t, System.out )</langsyntaxhighlight>
 
{{out}}
Line 1,537 ⟶ 1,928:
4,8,12,16,20,60
</pre>
 
=={{header|FutureBasic}}==
This Rosetta Code task calls for the use of the following CSV file:
 
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
 
While this file has column headers, it lacks row identifiers. The code below adds the missing row IDs. A screenshot of the output CSV file is shown as it appears when it's opened in the macOS Numbers spreadsheet application. An extra AVG column has been added which includes an average of the numbers in each respective row. It only required a single line of code.
 
<syntaxhighlight lang=futurebasic>
include "NSLog.incl"
 
include resources "rosetta_csv.csv"
 
/*
 
This ASCII text data is saved as a resource file
named "rosetta_csv.csv" in the application bundle.
 
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
 
*/
 
void local fn ManipulateCSV
CFURLRef url = fn BundleURLForResource( fn BundleMain, @"rosetta_csv", @"csv", NULL )
CFStringRef csvString = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
CFArrayRef csvArray = fn StringComponentsSeparatedByCharactersInSet( csvString, fn CharacterSetNewlineSet )
CFMutableStringRef mutStr = fn MutableStringWithCapacity(0)
long i
MutableStringAppendFormat( mutStr, @",%@,SUM,AVG\n", csvArray[0] )
for i = 1 to len(csvArray) - 1
CFArrayRef nums = fn StringComponentsSeparatedByString( csvArray[i], @"," )
CFNumberRef sum = fn ObjectValueForKeyPath( nums, @"@sum.self" )
CFNumberRef avg = fn ObjectValueForKeyPath( nums, @"@avg.self" )
MutableStringAppendFormat( mutStr, @"R%ld,%@,%@,%@\n",i,csvArray[i],sum,avg )
next
NSLog( @"%@", mutStr )
CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
url = fn URLByAppendingPathComponent( desktopURL, @"final_csv.csv" )
fn StringWriteToURL( mutStr, url, YES, NSUTF8StringEncoding, NULL )
end fn
 
fn ManipulateCSV
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:CSV_Manipulation.png]]
 
 
=={{header|Gambas}}==
<langsyntaxhighlight lang=gambas>Public Sub Form_Open()
Dim sData As String = File.Load("data.csv")
Dim sLine, sTemp As String
Line 1,570 ⟶ 2,020:
File.Save(User.home &/ "CSVData.csv", sData)
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,581 ⟶ 2,031:
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
 
import (
Line 1,638 ⟶ 2,088:
log.Fatal(err)
}
}</langsyntaxhighlight>
{{in|sample.csv}}
<pre>
Line 1,657 ⟶ 2,107:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang=groovy>def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
Line 1,664 ⟶ 2,114:
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')</langsyntaxhighlight>
 
csv_out.txt:
Line 1,677 ⟶ 2,127:
Array-based solution:
 
<langsyntaxhighlight lang=haskell>import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
Line 1,721 ⟶ 2,171:
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a</langsyntaxhighlight>
 
'''Solution 2'''
List-based solution, heavily using functors and lenses
<langsyntaxhighlight lang=haskell>{-# LANGUAGE FlexibleContexts,
TypeFamilies,
NoMonomorphismRestriction #-}
Line 1,773 ⟶ 2,223:
\2, 6, 10, 14, 18\n\
\3, 7, 11, 15, 19\n\
\4, 8, 12, 16, 20"</langsyntaxhighlight>
 
Examples:
Line 1,827 ⟶ 2,277:
 
3. Construction and combination
<langsyntaxhighlight lang=haskell>sampleSum = sample <||> (mkRow ["SUM"] <==> mkColumn sums)
where sums = map (show . sum) (read <$$> drop 1 (values sample))</langsyntaxhighlight>
 
<pre>λ> sampleSum
Line 1,841 ⟶ 2,291:
This version only works in Unicon, but can be easily adapted to work in Icon.
 
<langsyntaxhighlight lang=unicon>import Utils # To get CSV procedures
 
procedure main(A)
Line 1,851 ⟶ 2,301:
write(encodeCSV(csv))
}
end</langsyntaxhighlight>
 
Sample run:
Line 1,868 ⟶ 2,318:
Like other languages it is not necessary to use the csv utilities to accomplish this task.
 
<langsyntaxhighlight 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)
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data NB. format and write out amended data</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang=j> require 'tables/csv'
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 writecsv 'rc_outcsv.csv' NB. write out amended data. Strings are double-quoted</langsyntaxhighlight>
 
Adding a column with the sum of the rows:
<langsyntaxhighlight lang=j> require 'tables/csv'
'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
data=: <"0 (,. +/"1) makenum data NB. convert to numeric, sum rows & append column
(hdr,data) writecsv 'rc_out.csv'</langsyntaxhighlight>
 
Tacit version of above:
<langsyntaxhighlight lang=j> sumCSVrows=: writecsv~ (((<'SUM') ,~ {.) , [: (<"0)@(,. +/"1) makenum@}.)@readcsv
'rc_out.csv' sumCSVrows 'rc.csv'</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang=java>
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
</syntaxhighlight>
<syntaxhighlight lang=java>
public class CSV {
public static void main(String[] args) throws IOException {
CSV csv = new CSV("data.csv");
csv.sumAllRows();
csv.write();
}
 
private final File file;
private List<List<String>> data;
 
public CSV(File file) throws IOException {
this.file = file;
open();
}
 
/* convenience constructor */
public CSV(String path) throws IOException {
this(new File(path));
}
 
public void sumAllRows() {
appendColumn("SUM");
int sum;
int length;
for (int index = 1; index < data.size(); index++) {
sum = sum(data.get(index));
length = data.get(index).size();
data.get(index).set(length - 1, String.valueOf(sum));
}
}
 
private int sum(List<String> row) {
int sum = 0;
for (int index = 0; index < row.size() - 1; index++)
sum += Integer.parseInt(row.get(index));
return sum;
}
 
private void appendColumn(String title) {
List<String> titles = data.get(0);
titles.add(title);
/* append an empty cell to each row */
for (int index = 1; index < data.size(); index++)
data.get(index).add("");
}
 
private void open() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
data = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
/* using a limit of -1 will preserve trailing commas */
data.add(new ArrayList<>(List.of(line.split(",", -1))));
}
}
}
 
public void write() throws IOException {
try (FileWriter writer = new FileWriter(file)) {
String newline = System.lineSeparator();
for (List<String> row : data) {
writer.write(String.join(",", row));
writer.write(newline);
}
writer.flush();
}
}
}
</syntaxhighlight>
First iteration
<pre>
C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
4,8,12,16,20,60
</pre>
Second iteration
<pre>
C1,C2,C3,C4,C5,SUM,SUM
1,5,9,13,17,45,90
2,6,10,14,18,50,100
3,7,11,15,19,55,110
4,8,12,16,20,60,120
</pre>
<br />
===Roll Your Own===
<langsyntaxhighlight lang=java>import java.io.*;
import java.awt.Point;
import java.util.HashMap;
Line 1,995 ⟶ 2,541:
}
}
}</langsyntaxhighlight>
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 2,007 ⟶ 2,553:
{{libheader|Apache commons-csv}}
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
<langsyntaxhighlight lang=java>import java.io.*;
import java.util.*;
 
Line 2,132 ⟶ 2,678:
}
}
</syntaxhighlight>
</lang>
{{in}} data/csvtest_in.csv
<pre>
Line 2,151 ⟶ 2,697:
===uniVocity-parsers===
Using the [http://www.univocity.com/pages/parsers-tutorial uniVocity-parsers] library.
<langsyntaxhighlight lang=java>
public static void main(String[] args) throws IOException {
 
Line 2,183 ⟶ 2,729:
writer.writeRows(new ArrayList<List<Object>>());
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
Line 2,191 ⟶ 2,737:
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.
 
<langsyntaxhighlight lang=JavaScript>(function () {
'use strict';
 
Line 2,266 ⟶ 2,812:
);
 
})();</langsyntaxhighlight>
 
{{Out}}
Line 2,280 ⟶ 2,826:
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.
 
<langsyntaxhighlight lang=javascript>const fs = require('fs');
 
// formats for the data parameter in the function below: {col1: array | function, col2: array | function}
Line 2,320 ⟶ 2,866:
return idx;
}
});</langsyntaxhighlight>
 
{{output}}
Line 2,332 ⟶ 2,878:
 
=={{header|jq}}==
{{Worksworks with|jq|1.4}}
'''Works with gojq, the Go implementation of jq.'''
The following adds a column with header "SUM" as suggested in the task description.
 
The following adds a column with header "SUM" as suggested in the task description.
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.
It is assumed that the input has a header row.
<lang jq># Omit empty lines
For all other rows, the sum will simply be the last field of each output row.
<syntaxhighlight lang=jq>
# Input: a single row
# Omit empty rows
def read_csv:
if length>0 then split("\n,") else empty end ;
| map(if length>0 then split(",") else empty end) ;
 
# Input: an array
# add_column(label) adds a summation column (with the given label) to
# Output: the same array but with an additional summation column.
# the matrix representation of the CSV table, and assumes that all the
# If .[0] is a number, then it is assumed the entire row consists of numbers or numeric strings;
# entries in the body of the CSV file are, or can be converted to,
# otherwise, 0 is added
# numbers:
def add_column(label)add_sum:
(if .[0] | type == "number" then (map(tonumber) | add) else 0 end) as $sum
[.[0] + [label],
| (reduce. + .[1:][$sum] as $line;
 
([]; ($line|map(tonumber)) as $line | . + [$line + [$line|add]]))[] ] ;
# `tocsv` is only needed if fields should only be quoted by necessity:
def tocsv:
read_csv | add_column("SUM") | map(@csv)[]</lang>
map( if type == "string" and test("[,\"\r\n]") then "\"\(.)\"" else . end )
{{Out}}
| join(",");
$ jq -s -R -r -f CSV_data_manipulation.jq input.csv
 
"C1","C2","C3","C4","C5","SUM"
( input | read_csv | . + ["SUM"] | @csv),
1,5,9,13,17,45
(inputs | read_csv | add_sum | @csv)
2,6,10,14,18,50
</syntaxhighlight>
3,7,11,15,19,55
 
4,8,12,16,20,60
'''Invocation''': jq -Rn -r -f CSV_data_manipulation.jq input.csv
 
{{output}}
If jq's @csv builtin is used as shown in the program listing above, then every value will be quoted as shown here:
<pre>
"C1","C2","C3","C4","C5","SUM"
"1","5","9","13","17"
"2","6","10","14","18"
"3","7","11","15","19"
"4","8","12","16","20"
</pre>
If the calls to `@csv` are replaced by calls to `tocsv`, then the output would be:
<pre>
C1,C2,C3,C4,C5,SUM
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang=Julia>using DataFrames, CSV
 
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
 
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
</langsyntaxhighlight>{{out}}
<pre>
$ cat csv_data_manipulation_out.dat
Line 2,379 ⟶ 2,947:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>// version 1.1.3
 
import java.io.File
Line 2,392 ⟶ 2,960:
File("example2.csv").writeText(text) // write to new file
println(text) // print to console
}</langsyntaxhighlight>
 
{{out}}
Line 2,404 ⟶ 2,972:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang=lingo>----------------------------------------
-- Simplified CSV parser (without escape character support etc.).
-- First line is interrepted as header with column names.
Line 2,502 ⟶ 3,070:
delete char (str.length-delim.length+1) to str.length of str
return str
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang=lingo>sep = ","
eol = numtochar(10)
 
Line 2,547 ⟶ 3,115:
3,7,11,15,19,55
4,8,12,16,20,60
"</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo|6.2.4}}
UCBLogo has no built-in support for generic CSV files.
 
<syntaxhighlight lang="logo">to csv.data.manipulation :in :out
local [header line list sum]
openread :in
setread :in
openwrite :out
setwrite :out
make "header readword
print word :header ",SUM
while [not eofp] [
make "line readword
make "list parse map [ifelse equalp ? ", ["\ ] [?]] :line
make "sum apply "sum :list
print (word :line "\, :sum)
]
close :in
setread []
close :out
setwrite []
end</syntaxhighlight>
 
<syntaxhighlight lang="logo">csv.data.manipulation "data.csv "output.csv</syntaxhighlight>
 
{{out}}
<pre>
Contents of output.csv
 
C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
4,8,12,16,20,60
</pre>
 
=={{header|Lua}}==
Adds a SUM column.
<langsyntaxhighlight lang=lua>local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
Line 2,582 ⟶ 3,187:
local file=io.open('file.csv', 'w')
file:write(newFileData)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,593 ⟶ 3,198:
 
=={{header|M2000 Interpreter}}==
<langsyntaxhighlight lang=M2000 Interpreter>
Module Checkit {
Function Sum {
Line 2,641 ⟶ 3,246:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
Entire script:
<langsyntaxhighlight lang=Maple>M := ImportMatrix("data.csv",source=csv);
M(..,6) := < "Total", seq( add(M[i,j], j=1..5), i=2..5 ) >;
ExportMatrix("data_out.csv",M,target=csv);
</syntaxhighlight>
</lang>
 
Running this script showing interactive results:
<langsyntaxhighlight lang=Maple>> M := ImportMatrix("data.csv",source=csv);
["C1" "C2" "C3" "C4" "C5"]
[ ]
Line 2,675 ⟶ 3,280:
> ExportMatrix("data_out.csv",M,target=csv);
96
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica's Import and Export functions support CSV files.
<langsyntaxhighlight 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}}
iCSV[[1, 1]] = Column0;Transpose@
Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]];
iCSV[[2, 2]] = 100;
iCSV[[3, 3]]// = 200;MatrixForm
Export["test.csv",iCSV];</syntaxhighlight>
iCSV[[4, 4]] = 300;
iCSV[[5, 5]] = 400;
iCSV[[2, 3]] = 60;
Export["test.csv",iCSV];</lang>
{{out}}
<pre>Column0,(C1 C2, C3, C4, C5 Sum
1,100,60, 5 9 13, 17 45
2, 6,200, 10 14, 18 50
3, 7, 11,300, 15 19 55
4, 8, 12, 16,400</pre> 20 60
 
)</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
=== Using file manipulation ===
<langsyntaxhighlight lang=Matlab>filename='data.csv';
fid = fopen(filename);
header = fgetl(fid);
Line 2,709 ⟶ 3,313:
fprintf(fid,"%i\n",sum(X(k,:)));
end;
fclose(fid);</langsyntaxhighlight>
 
=== Using <code>table</code> ===
<langsyntaxhighlight lang=Matlab>filename='data.csv';
data = readtable(filename);
data.SUM = sum([data{:,:}],2);
writetable(data,filename);</langsyntaxhighlight>
 
=={{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 '~'
<langsyntaxhighlight lang=Nanoquery>def sum(record)
sum = 0
Line 2,736 ⟶ 3,340:
end for
write</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Line 2,742 ⟶ 3,346:
{{libheader|Apache commons-csv}}
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
<langsyntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols
 
Line 2,864 ⟶ 3,468:
end
return lineOut
</syntaxhighlight>
</lang>
{{in}} data/csvtest_in.csv
<pre>
Line 2,886 ⟶ 3,490:
Nim's standard library contains a robust CSV parser, but for this simple document that's not necessary.
 
<langsyntaxhighlight lang=nim>import strutils, streams
 
let
Line 2,902 ⟶ 3,506:
line.add(",SUM")
else:
var tmpsum = 0
for n in split(line, ","):
tmpsum += parseInt(n)
line.add(",")
line.add($tmpsum)
outf.writeLnwriteLine($line)
 
inc lineNumber</langsyntaxhighlight>
 
{{out}}
Line 2,924 ⟶ 3,528:
Objeck has a CSV parser with built-in functions.
 
<langsyntaxhighlight lang=objeck>use System.IO.File;
use Data.CSV;
 
Line 2,956 ⟶ 3,560:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,966 ⟶ 3,570:
4,8,12,16,20,60
</pre>
 
 
 
=={{header|OCaml}}==
Using the '''csv''' module available in '''Opam''':
 
<syntaxhighlight lang=ocaml>let list_add_last this lst =
List.rev (this :: (List.rev lst))
 
let () =
let csv = Csv.load "data.csv" in
let fields, data =
(List.hd csv,
List.tl csv)
in
let fields =
list_add_last "SUM" fields
in
let sums =
List.map (fun row ->
let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in
list_add_last (string_of_int tot) row
) data
in
Csv.output_all (Csv.to_channel stdout) (fields :: sums)</syntaxhighlight>
 
{{out}}
<pre>
$ opam install csv
$ ocaml -I $(ocamlfind query csv) csv.cma rc_csv.ml
C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
4,8,12,16,20,60
</pre>
 
 
=={{header|PARI/GP}}==
Line 2,972 ⟶ 3,613:
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang=parigp>
\\ CSV data manipulation
\\ 10/24/16 aev
Line 2,991 ⟶ 3,632:
\\ Testing:
processCsv("c:\\pariData\\test");
</syntaxhighlight>
</lang>
 
{{in}} data/test.csv file
Line 3,012 ⟶ 3,653:
{{works with|Free Pascal}}
In Pascal you can use TStringList CommaText property to work with CSV.
<langsyntaxhighlight lang=pascal>
program CSV_Data_Manipulation;
uses Classes, SysUtils;
Line 3,058 ⟶ 3,699:
ts.Free;
end.
</syntaxhighlight>
</lang>
 
{{in}} input.csv file
Line 3,078 ⟶ 3,719:
=={{header|Perl}}==
For simple files, you can use [http://p3rl.org/split split]:
<langsyntaxhighlight lang=perl>#!/usr/bin/perl
use warnings;
use strict;
Line 3,116 ⟶ 3,757:
print join(',' => @header), "\n";
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:
<langsyntaxhighlight lang=perl>#!/usr/bin/perl
use warnings;
use strict;
Line 3,143 ⟶ 3,784:
 
# Print the output.
$csv->print(*STDOUT, $_) for \@header, @rows;</langsyntaxhighlight>
 
=={{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.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>integer fn = open("test.csv","r")
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence lines = {}
<span style="color: #008080;">constant</span> <span style="color: #000000;">tcsv</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
while 1 do
C1,C2,C3,C4,C5
object line = gets(fn)
1,5,9,13,17
if atom(line) then exit end if
2,6,10,14,18
lines = append(lines,split(trim(line),','))
3,7,11,15,19
end while
4,8,12,16,20
close(fn)
"""</span>
lines[1] = join(lines[1],',')&",SUM"
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tcsv</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">):</span><span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.csv"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_LF_STRIPPED</span><span style="color: #0000FF;">))</span>
for i=2 to length(lines) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
sequence s = lines[i]
<span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]),</span><span style="color: #008000;">','</span><span style="color: #0000FF;">)</span>
for j=1 to length(s) do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
{{s[j]}} = scanf(s[j],"%d")
<span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #008000;">','</span><span style="color: #0000FF;">)&</span><span style="color: #008000;">",SUM"</span>
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
-- s[rand(length(s))] = rand(100) -- (if you like)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]),</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
lines[i] = sprintf("%d,%d,%d,%d,%d,%d",s&sum(s))
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">t</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
lines = join(lines,'\n')
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
fn = open("out.csv","w")
<span style="color: #000080;font-style:italic;">-- s[rand(length(s))] = rand(100) -- (if you like)</span>
puts(fn,lines)
<span style="color: #000000;">t</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
close(fn)
<span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d,%d,%d,%d,%d,%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
puts(1,lines)</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"out.csv"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"w"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,180 ⟶ 3,830:
=={{header|PHP}}==
 
<langsyntaxhighlight lang=PHP>
<?php
 
Line 3,216 ⟶ 3,866:
$row++;
}
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(in "data.csv"
(prinl (line) "," "SUM")
(while (split (line) ",")
(prinl (glue "," @) "," (sum format @)) ) )</langsyntaxhighlight>
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,231 ⟶ 3,881:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang=pli>*process source xref attributes or(!);
csv: Proc Options(Main);
/*********************************************************************
Line 3,295 ⟶ 3,945:
End;
 
End;</langsyntaxhighlight>
{{in}}
<pre>
Line 3,314 ⟶ 3,964:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang=PowerShell>## Create a CSV file
@"
C1,C2,C3,C4,C5
Line 3,347 ⟶ 3,997:
## Display the object in tabular form
$records | Format-Table -AutoSize
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,363 ⟶ 4,013:
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.
<langsyntaxhighlight lang=Prolog>test :- augment('test.csv', 'test.out.csv').
 
% augment( +InFileName, +OutFileName)
Line 3,385 ⟶ 4,035:
append(List, [Sum], NewList),
NewTerm =.. [F | NewList].
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>
EnableExplicit
 
Line 3,440 ⟶ 4,090:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out|Output (in output.csv)}}
Line 3,455 ⟶ 4,105:
=== 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.
<langsyntaxhighlight lang=python>import fileinput
 
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
Line 3,465 ⟶ 4,115:
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')</langsyntaxhighlight>
{{out}}
After this the data file <code>csv_data_manipulation.csv</code> gets changed from that of the task to:
Line 3,476 ⟶ 4,126:
=== 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.
<langsyntaxhighlight lang=python>import csv
from pathlib import Path
from tempfile import NamedTemporaryFile
Line 3,498 ⟶ 4,148:
temp_file_path = Path(temp_file.name)
temp_file_path.replace(filepath)
</syntaxhighlight>
</lang>
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,507 ⟶ 4,157:
 
=== Using <code>pandas</code> ===
<langsyntaxhighlight lang=python>import pandas as pd
 
filepath = 'data.csv'
Line 3,514 ⟶ 4,164:
rows_sums = df.sum(axis=1)
df['SUM'] = rows_sums
df.to_csv(filepath, index=False)</langsyntaxhighlight>
 
=={{header|Q}}==
<langsyntaxhighlight 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
`:output.csv 0: csv 0: t / Write updated table as CSV to output.csv</langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight lang=rsplus>
df <- read.csv(textConnection(
"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"))
 
df <- transform(df,SUM = rowSums(df))
 
write.csv(df,row.names = FALSE)
</lang>
 
=====Slightly different way of doing the above=====
<lang rsplus>
df <- read.csv(textConnection(
"C1,C2,C3,C4,C5
Line 3,546 ⟶ 4,182:
df$sum <- rowSums(df)
write.csv(df,row.names = FALSE)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,558 ⟶ 4,194:
 
This output can also be saved to a file:
<syntaxhighlight lang=R> write.csv(df, file = "foo.csv",row.names = FALSE)
 
</syntaxhighlight>
<lang R> write.csv(df,row.names = FALSE,file = "foo.csv") </lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>#lang racket
(require (planet neil/csv:1:=7) net/url)
 
Line 3,578 ⟶ 4,214:
(append row (list (~a (apply + xs))))))
(define (->string row) (string-join row "," #:after-last "\n"))
(string-append* (map ->string (cons head rows))))</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang=racket>(define csv-file
"C1, C2, C3, C4, C5
1, 5, 9, 13, 17
Line 3,587 ⟶ 4,223:
4, 8, 12, 16, 20")
 
(display (all-rows (open-input-string csv-file)))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,600 ⟶ 4,236:
(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.
<syntaxhighlight lang=raku perl6line>my $csvfile = './whatever.csv';
my $fh = open($csvfile, :r);
my @header = $fh.get.split(',');
Line 3,609 ⟶ 4,245:
$out.say((@header,'SUM').join(','));
$out.say((@$_, [+] @$_).join(',')) for @csv;
close $out;</langsyntaxhighlight>
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.)
<syntaxhighlight lang=raku perl6line>use Text::CSV;
my $csvfile = './whatever.csv';
my @csv = Text::CSV.parse-file($csvfile);
# modify(@csv); # do whatever;
csv-write-file( @csv, :file($csvfile) );</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight lang=Red>>>filein: read/lines %file.csv
>>data: copy []
>>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"]]</langsyntaxhighlight>
 
<langsyntaxhighlight lang=Red>>>forall data [either (index? data) = 1[
append data/1 "SUM"
][
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)
]]</langsyntaxhighlight>
<langsyntaxhighlight lang=Red>>>foreach item data [append item/6 "^/" repeat c 5 [append item/:c ","]]
>> print data
C1, C2, C3, C4, C5, SUM
Line 3,636 ⟶ 4,272:
3, 7, 11, 15, 19, 55
4, 8, 12, 16, 20, 60
>>write fileout.csv form data</langsyntaxhighlight>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang=rexx>/* REXX ***************************************************************
* extend in.csv to add a column containing the sum of the lines' elems
* 21.06.2013 Walter Pachl
Line 3,663 ⟶ 4,299:
Do i=1 To i-1
Call lineout csv,l.i
End</langsyntaxhighlight>
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,676 ⟶ 4,312:
 
Also supported is the ability to specify the fileID of the data file to be specified.
<langsyntaxhighlight 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*/
if iFID=='' | iFID=="," then iFID= 'CSV_SUM.DAT' /*Not specified? Then use the default*/
Line 3,694 ⟶ 4,330:
do k=2 for rec-2 /*process all the records just read. */
call lineout iFID,@.k /*write the new CSV record (has SUM). */
end /*k*/ /*stick a fork in it, we're all done.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; to the console:}}
<pre>
Line 3,702 ⟶ 4,338:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
# Project : CSV data manipulation
 
Line 3,737 ⟶ 4,373:
fclose(fpout)
see csvend + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,748 ⟶ 4,384:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang=ruby>require 'csv'
# read:
ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible.
Line 3,759 ⟶ 4,395:
CSV.open("out.csv", 'w') do |csv|
ar.each{|line| csv << line}
end</langsyntaxhighlight>
{{output}}
<pre>c1,c2,c3,c4,c5,SUM
Line 3,768 ⟶ 4,404:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>csv$ = "C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
Line 3,801 ⟶ 4,437:
cma$ = ""
print
next r</langsyntaxhighlight>
<pre>C1,C2,C3,C4,C5
1,5,9,13,17
Line 3,819 ⟶ 4,455:
=={{header|Rust}}==
{{libheader|BurntSushi's csv crate}}
<langsyntaxhighlight lang=rust>use std::error::Error;
use std::num::ParseIntError;
use csv::{Reader, Writer};
Line 3,846 ⟶ 4,482:
writer.flush()?;
Ok(())
}</langsyntaxhighlight>
{{output}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,855 ⟶ 4,491:
 
=={{header|SAS}}==
<langsyntaxhighlight lang=sas>data _null_;
infile datalines dlm="," firstobs=2;
file "output.csv" dlm=",";
Line 3,869 ⟶ 4,505:
4,8,12,16,20
;
run;</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight lang=Scala>import scala.io.Source
 
object parseCSV extends App {
Line 3,900 ⟶ 4,536:
 
*/
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 3,906 ⟶ 4,542:
is in the same directory as the program.
 
<langsyntaxhighlight lang=seed7>$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,922 ⟶ 4,558:
writeln(join(csvData[line], ","));
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,934 ⟶ 4,570:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang=sensetalk>
// For test purposes, start by creating (or re-creating) the data file
put {{
Line 3,960 ⟶ 4,596:
put file "myData.csv" -- display the updated file contents
 
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
{{trans|Raku}}
For simple files we can use the ''split'' method.
<langsyntaxhighlight lang=ruby># Read
var csvfile = %f'data.csv';
var fh = csvfile.open_r;
Line 3,976 ⟶ 4,612:
out.say([header..., 'SUM'].join(','));
csv.each { |row| out.say([row..., row.sum].join(',')) };
out.close;</langsyntaxhighlight>
 
For complex files, the ''Text::CSV'' library is recommended.
<langsyntaxhighlight lang=ruby>var csv = require('Text::CSV').new(
Hash(eol => "\n")
);
Line 4,002 ⟶ 4,638:
[header, rows...].each { |row|
csv.print(out, row);
};</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang=stata>import delim input.csv, clear
replace c5=c3+c4
egen sum=rowtotal(c*)
drop if mod(c3,3)==0
export delim output.csv, replace</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{tcllib|struct::matrix}}
{{tcllib|csv}}
<langsyntaxhighlight lang=tcl>package require struct::matrix
package require csv
 
Line 4,042 ⟶ 4,678:
}
 
addSumColumn "example.csv"</langsyntaxhighlight>
{{out|Output (in <tt>example.csv</tt>)}}
<pre>
Line 4,053 ⟶ 4,689:
 
Although, for this specific small task,
<langsyntaxhighlight lang=tcl>set f [open example.csv r]
puts "[gets $f],SUM"
while { [gets $f row] > 0 } {
puts "$row,[expr [string map {, +} $row]]"
}
close $f</langsyntaxhighlight>
suffices.
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang=tuscript>
$$ MODE DATA
$$ csv=*
Line 4,081 ⟶ 4,717:
csv=APPEND(csv,line)
ENDLOOP
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,092 ⟶ 4,728:
 
=={{header|TXR}}==
<langsyntaxhighlight lang=txr>@(coll)@{name /[^,]+/}@(end)
@(collect :vars (value sum))
@ (bind sum 0)
Line 4,103 ⟶ 4,739:
@ (end)
@(end)
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
 
<lang bash>exec 0<"$1" # open the input file on stdin
Very simple solution using powerfull and ancient but strong linux command, I named "tr" and "bc", and internal variable bash test capabilities :
<syntaxhighlight lang=text>cat csv | while read S; do
[ -z ${S##*C*} ] && echo $S,SUM || echo $S,`echo $S | tr ',' '+' | bc`
done</syntaxhighlight>
 
Result :
<syntaxhighlight lang=text>C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
4,8,12,16,20,60</syntaxhighlight>
 
Other solution (not from me) :
 
<syntaxhighlight lang=text>bash>exec 0<"$1" # open the input file on stdin
exec 1>"$1.new" # open an output file on stdout
{
Line 4,126 ⟶ 4,777:
} &&
mv "$1" "$1.bak" &&
mv "$1.new" "$1"</langsyntaxhighlight>
 
{{works with|ksh}}
Line 4,134 ⟶ 4,785:
read -A
 
=={{header|uBasic/4tH}}==
{{works with|R3}}
uBasic/4tH can read text files and has a built-in tokenizer, so parsing simple CSV files is not a problem.
<syntaxhighlight lang=text>if set (a, open ("yourcsv.csv", "r")) < 0 then
print "Cannot open \qyourcsv.csv\q" ' open file a for reading
end ' abort on file opening errors
endif
 
if set (b, open ("mycsv.csv", "w")) < 0 then
print "Cannot open \qmycsv.csv\q" ' open file a for writing
end ' abort on file opening errors
endif
 
if read (a) = 0 then ' read the header line
print "Unexpected end of file" ' if it fails, write the error
close a : close b : end ' close files and terminate
endif
' process the header line
for c = 0 step 1 ' don't know number of columns
p = here() ' get input buffer position
y = tok (ord (",")) ' parse the first field
until p = here() ' until buffer position doesn't change
write b, show (y);","; ' write it out
next
 
write b, "Sum" ' add a column
 
do while read (a) ' read a line
s = 0 ' reset the sum
for x = 0 to c-1 ' read all columns
y = iif (set (y, val (tok (ord (",")))) = info ("nil"), 0, y)
s = s + y ' add value to sum
write b, y;","; ' write the value
next ' next column
write b, s ' write the sum
loop
 
close a : close b : end ' close files and terminate
</syntaxhighlight>
=={{header|Ursa}}==
<langsyntaxhighlight lang=ursa>#
# csv data manipulation
#
Line 4,176 ⟶ 4,866:
for (set i 0) (< i (size lines)) (inc i)
out lines<i> endl f
end for</langsyntaxhighlight>
 
=={{header|VBA}}==
Using Excel VBA to load a CSV file in a new workbook.
 
<langsyntaxhighlight lang=vb>Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Line 4,187 ⟶ 4,877:
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang=vb>'Instatiate FSO.
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.
Line 4,224 ⟶ 4,914:
AddElements = AddElements + CInt(arr(i))
Next
End Function</langsyntaxhighlight>
 
{{In}}
Line 4,244 ⟶ 4,934:
=={{header|Vedit macro language}}==
This example adds 100 to the values in each cell at row n+1, column n.
<langsyntaxhighlight lang=vedit>File_Open("input.csv")
for (#1 = 0; #1 < 4; #1++) {
Goto_Line(#1+2) // line (starting from line 2)
Line 4,254 ⟶ 4,944:
Num_Ins(#2+100, LEFT+NOCR) // write new value
}
File_Save_As("output.csv", OK+NOMSG) </langsyntaxhighlight>
output.csv:
<pre>
Line 4,265 ⟶ 4,955:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang=vfp>
CLOSE DATABASES ALL
SET SAFETY OFF
Line 4,277 ⟶ 4,967:
MODIFY FILE file2.csv NOEDIT IN SCREEN
SET SAFETY ON
</syntaxhighlight>
</lang>
 
=={{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.
<syntaxhighlight lang="wren">import "io" for File
 
var lines = File.read("rc.csv").split("\n").map { |w| w.trim() }.toList
 
var file = File.create("rc.csv") // overwrite existing file
file.writeBytes(lines[0] + ",SUM\n")
for (line in lines.skip(1)) {
if (line != "") {
var nums = line.split(",").map { |s| Num.fromString(s) }
var sum = nums.reduce { |acc, n| acc + n }
file.writeBytes(line + ",%(sum)\n")
}
}
file.close()</syntaxhighlight>
 
{{out}}
Contents of rc.csv after manipulation:
<pre>
C1,C2,C3,C4,C5,SUM
1,5,9,13,17,45
2,6,10,14,18,50
3,7,11,15,19,55
4,8,12,16,20,60
</pre>
 
=={{header|XPL0}}==
XPL0 has no built-in functions that handle CSV files. However, it's easy
enough to make the InField procedure shown here that reads in a CSV field
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
<syntaxhighlight lang=XPL0>string 0; \use zero-terminated strings
def LF=$0A, EOF=$1A;
int Val, Char;
char Str(80);
 
proc InField;
int I;
[I:= 0; Val:= 0;
loop [Char:= ChIn(1);
if Char=^, or Char=LF or Char=EOF then quit;
Str(I):= Char;
I:= I+1;
if Char>=^0 and Char<=^9 then
Val:= Val*10 + Char - ^0;
];
Str(I):= 0;
];
 
int Sum;
[loop [InField;
Text(0, Str);
if Char = LF then quit;
ChOut(0, ^,);
];
Text(0, ",SUM");
CrLf(0);
loop [Sum:= 0;
loop [InField;
if Char = EOF then return;
if rem(Val/5)=0 then Val:= Val*20;
IntOut(0, Val);
Sum:= Sum + Val;
if Char = LF then quit;
ChOut(0, ^,);
];
Text(0, ",");
IntOut(0, Sum);
CrLf(0);
];
]</syntaxhighlight>
 
{{out}}
<pre>
C1,C2,C3,C4,C5,SUM
1,100,9,13,17,140
2,6,200,14,18,240
3,7,11,300,19,340
4,8,12,16,400,440
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<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
 
line input #1 header$
header$ = header$ + ",SUM"
print #2 header$
 
while !eof(1)
input #1 c1, c2, c3, c4, c5
sum = c1 + c2 + c3 + c4 + c5
print #2 c1, c2, c3, c4, c5, sum
wend
 
close #1
close #2
end</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang=zkl>csvFile:=File("test.csv");
header:=csvFile.readln().strip(); // remove trailing "\n" and leading white space
listOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(",").apply("toInt") });
Line 4,287 ⟶ 5,078:
newFile.writeln(header + ",sum");
listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(","),",",ns.sum()) });
newFile.close();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,297 ⟶ 5,088:
4,8,12,16,20,60
</pre>
 
[[Category:CSV]]
Cookies help us deliver our services. By using our services, you agree to our use of cookies.