CSV data manipulation: Difference between revisions
→{{header|Logo}}
(48 intermediate revisions by 31 users not shown) | |||
Line 27:
=={{header|11l}}==
<
I L.index == 0
line ‘’= ‘,SUM’
E
line ‘’= ‘,’sum(line.split(‘,’).map(
print(line)</
{{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):
<
type Row(<>) is tagged private;
Line 65:
Sep: Character;
end record;
end CSV;</
The implementation of the package is
<
function Line(S: String; Separator: Character := ',')
Line 92:
end Next;
end CSV;</
Finally, the main program which uses the package CSV:
<
procedure CSV_Data_Manipulation is
Line 114:
end;
end loop;
end CSV_Data_Manipulation;</
{{out}}
Line 126:
=={{header|Aime}}==
<
read_csv(list t, text path)
{
Line 198:
return 0;
}</
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 207:
=={{header|ALGOL 68}}==
<
PROC char count = (CHAR c, STRING str) INT:
BEGIN
Line 294:
print ((join (fields, ","), new line))
OD;
close (foo)</
{{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}}==
<
{
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</
'''Output:'''
<pre>C1,C2,C3,C4,C5
Line 321 ⟶ 347:
=={{header|AWK}}==
adds a column sum to a csv table
<
BEGIN { FS = OFS = "," }
NR==1 {
Line 333 ⟶ 359:
}
print $0, sum
}</
<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>
#define TITLE "CSV data manipulation"
Line 619 ⟶ 712:
return 0;
}
</syntaxhighlight>
{{out|Output (in <tt>tmp/csv-data-manipulation.result.csv</tt>)}}
<pre>
Line 627 ⟶ 720:
3,7,11,300,19
4,8,12,16,400
</pre>
==={{libheader|Gadget}}===
<syntaxhighlight lang="c">
#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;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
</syntaxhighlight>
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Column0,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|C++}}==
<
#include <vector>
#include <iostream>
Line 758 ⟶ 982:
oCSV.save( "test_out.csv" );
return 0;
}</
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 766 ⟶ 990:
3,7,11,300,19
4,8,12,16,400
</pre>
=={{header|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>
{{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.
<
(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>
{{out|Output (in <code>results.txt</code>)}}
Line 882 ⟶ 1,187:
=={{header|D}}==
<
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)));
}</
{{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}}==
<
;; CSV -> LISTS
(define (csv->row line) (map (lambda(x) (or (string->number x) x)) (string-split line ",")))
Line 922 ⟶ 1,313:
</syntaxhighlight>
{{out}}
<
(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>
=={{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);</
{{Out}} (contents of Rosetta::myNewCSVFile):
<pre>C1x,C2y,C3z,C4a,C5b
Line 972 ⟶ 1,363:
=={{header|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>
{{Out}}
Line 1,036 ⟶ 1,427:
=={{header|Erlang}}==
<
-module( csv_data ).
Line 1,073 ⟶ 1,464:
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
</syntaxhighlight>
{{out}}
Line 1,085 ⟶ 1,476:
</pre>
=={{header|Euphoria
<
--- with trace
-- trace(0)
Line 1,177 ⟶ 1,568:
main()
</syntaxhighlight>
{{out}}
Line 1,190 ⟶ 1,581:
=={{header|F_Sharp|F#}}==
<
[<EntryPoint>]
Line 1,204 ⟶ 1,595:
File.WriteAllLines ("test_out.csv", output)
0
</syntaxhighlight>
{{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.
<
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</
{{out}}
Contents of <code>example.csv</code>
Line 1,236 ⟶ 1,627:
</pre>
=={{
<
\ USAGE:
\ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv
Line 1,285 ⟶ 1,676:
THEN
2DROP 2DROP
;</
{{out}}
<pre>
Line 1,294 ⟶ 1,685:
4,8,12,16,20,60.000</pre>
=={{
=== Fortran 2003 ===
It's fairly easy to read arbitrary lines using allocatable character strings, available since Fortran 2003.
<
implicit none
character(:), allocatable :: line, name, a(:)
Line 1,404 ⟶ 1,795:
array(p) = line(k:n)
end subroutine
end program</
=== 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.
<
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>
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}}==
<
Open "manip.csv" For Input As #1 ' existing CSV file
Line 1,468 ⟶ 1,859:
Close #1
Close #2</
{{out}}
Line 1,482 ⟶ 1,873:
=={{header|FunL}}==
<
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 )</
{{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}}==
<
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</
Output:
<pre>
Line 1,581 ⟶ 2,031:
=={{header|Go}}==
<
import (
Line 1,638 ⟶ 2,088:
log.Fatal(err)
}
}</
{{in|sample.csv}}
<pre>
Line 1,657 ⟶ 2,107:
=={{header|Groovy}}==
<
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')</
csv_out.txt:
Line 1,677 ⟶ 2,127:
Array-based solution:
<
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</
'''Solution 2'''
List-based solution, heavily using functors and lenses
<
TypeFamilies,
NoMonomorphismRestriction #-}
Line 1,773 ⟶ 2,223:
\2, 6, 10, 14, 18\n\
\3, 7, 11, 15, 19\n\
\4, 8, 12, 16, 20"</
Examples:
Line 1,827 ⟶ 2,277:
3. Construction and combination
<
where sums = map (show . sum) (read <$$> drop 1 (values sample))</
<pre>λ> sampleSum
Line 1,841 ⟶ 2,291:
This version only works in Unicon, but can be easily adapted to work in Icon.
<
procedure main(A)
Line 1,851 ⟶ 2,301:
write(encodeCSV(csv))
}
end</
Sample run:
Line 1,868 ⟶ 2,318:
Like other languages it is not necessary to use the csv utilities to accomplish this task.
<
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</
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:
<
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</
Adding a column with the sum of the rows:
<
'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'</
Tacit version of above:
<
'rc_out.csv' sumCSVrows 'rc.csv'</
=={{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===
<
import java.awt.Point;
import java.util.HashMap;
Line 1,995 ⟶ 2,541:
}
}
}</
{{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.
<
import java.util.*;
Line 2,132 ⟶ 2,678:
}
}
</syntaxhighlight>
{{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.
<
public static void main(String[] args) throws IOException {
Line 2,183 ⟶ 2,729:
writer.writeRows(new ArrayList<List<Object>>());
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 2,192 ⟶ 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.
<
'use strict';
Line 2,267 ⟶ 2,812:
);
})();</
{{Out}}
Line 2,281 ⟶ 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.
<
// formats for the data parameter in the function below: {col1: array | function, col2: array | function}
Line 2,321 ⟶ 2,866:
return idx;
}
});</
{{output}}
Line 2,333 ⟶ 2,878:
=={{header|jq}}==
{{
'''Works with gojq, the Go implementation of jq.'''
The following adds a column with header "SUM" as suggested in the task description.
It is assumed that the input has a header row.
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("
# Input: an array
# Output: the same array but with an additional summation column.
# If .[0] is a number, then it is assumed the entire row consists of numbers or numeric strings;
# otherwise, 0 is added
def
(if .[0] | type == "number" then (map(tonumber) | add) else 0 end) as $sum
|
# `tocsv` is only needed if fields should only be quoted by necessity:
def tocsv:
map( if type == "string" and test("[,\"\r\n]") then "\"\(.)\"" else . end )
| join(",");
( input | read_csv | . + ["SUM"] | @csv),
(inputs | read_csv | add_sum | @csv)
</syntaxhighlight>
'''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}}==
<syntaxhighlight 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)
</syntaxhighlight>{{out}}
<pre>
$ cat csv_data_manipulation_out.dat
Line 2,390 ⟶ 2,947:
=={{header|Kotlin}}==
<
import java.io.File
Line 2,403 ⟶ 2,960:
File("example2.csv").writeText(text) // write to new file
println(text) // print to console
}</
{{out}}
Line 2,415 ⟶ 2,972:
=={{header|Lingo}}==
<
-- Simplified CSV parser (without escape character support etc.).
-- First line is interrepted as header with column names.
Line 2,513 ⟶ 3,070:
delete char (str.length-delim.length+1) to str.length of str
return str
end</
<
eol = numtochar(10)
Line 2,558 ⟶ 3,115:
3,7,11,15,19,55
4,8,12,16,20,60
"</
=={{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.
<
for line in io.lines('file.csv') do
table.insert(csv, {})
Line 2,593 ⟶ 3,187:
local file=io.open('file.csv', 'w')
file:write(newFileData)
</syntaxhighlight>
{{out}}
Line 2,602 ⟶ 3,196:
4,8,12,16,20,60
</pre>
=={{header|M2000 Interpreter}}==
<
Module Checkit {
Function Sum {
Line 2,653 ⟶ 3,246:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
Entire script:
<
M(..,6) := < "Total", seq( add(M[i,j], j=1..5), i=2..5 ) >;
ExportMatrix("data_out.csv",M,target=csv);
</syntaxhighlight>
Running this script showing interactive results:
<
["C1" "C2" "C3" "C4" "C5"]
[ ]
Line 2,705 ⟶ 3,280:
> ExportMatrix("data_out.csv",M,target=csv);
96
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica's Import and Export functions support CSV files.
<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}}
iCSV = Transpose@
Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]];
iCSV // MatrixForm
Export["test.csv",iCSV];</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|MATLAB}} / {{header|Octave}}==
=== Using file manipulation ===
<
fid = fopen(filename);
header = fgetl(fid);
Line 2,721 ⟶ 3,313:
fprintf(fid,"%i\n",sum(X(k,:)));
end;
fclose(fid);</
=== Using <code>table</code> ===
<
data = readtable(filename);
data.SUM = sum([data{:,:}],2);
writetable(data,filename);</
=={{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 '~'
<syntaxhighlight lang=Nanoquery>def sum(record)
sum = 0
for i in range(1,
sum = sum + int(record ~ i)
end for
return
end def
open "file.csv"
add "SUM"
for
(
end for
write</
=={{header|NetRexx}}==
Line 2,754 ⟶ 3,346:
{{libheader|Apache commons-csv}}
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
<
options replace format comments java crossref symbols
Line 2,876 ⟶ 3,468:
end
return lineOut
</syntaxhighlight>
{{in}} data/csvtest_in.csv
<pre>
Line 2,898 ⟶ 3,490:
Nim's standard library contains a robust CSV parser, but for this simple document that's not necessary.
<
let
Line 2,914 ⟶ 3,506:
line.add(",SUM")
else:
var
for n in split(line, ","):
line.add(",")
line.add($
outf.
inc lineNumber</
{{out}}
Line 2,936 ⟶ 3,528:
Objeck has a CSV parser with built-in functions.
<
use Data.CSV;
Line 2,968 ⟶ 3,560:
}
}
</syntaxhighlight>
{{out}}
Line 2,978 ⟶ 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,984 ⟶ 3,613:
{{Works with|PARI/GP|2.7.4 and above}}
<
\\ CSV data manipulation
\\ 10/24/16 aev
Line 3,003 ⟶ 3,632:
\\ Testing:
processCsv("c:\\pariData\\test");
</syntaxhighlight>
{{in}} data/test.csv file
Line 3,024 ⟶ 3,653:
{{works with|Free Pascal}}
In Pascal you can use TStringList CommaText property to work with CSV.
<
program CSV_Data_Manipulation;
uses Classes, SysUtils;
Line 3,070 ⟶ 3,699:
ts.Free;
end.
</syntaxhighlight>
{{in}} input.csv file
Line 3,090 ⟶ 3,719:
=={{header|Perl}}==
For simple files, you can use [http://p3rl.org/split split]:
<
use warnings;
use strict;
Line 3,128 ⟶ 3,757:
print join(',' => @header), "\n";
print join(',' => @$_), "\n" for @rows;
</syntaxhighlight>
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:
<
use warnings;
use strict;
Line 3,155 ⟶ 3,784:
# Print the output.
$csv->print(*STDOUT, $_) for \@header, @rows;</
=={{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)-->
<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;">"""
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
"""</span>
<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>
<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>
<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>
<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: #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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- s[rand(length(s))] = rand(100) -- (if you like)</span>
<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>
<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>
<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,211 ⟶ 3,830:
=={{header|PHP}}==
<
<?php
Line 3,247 ⟶ 3,866:
$row++;
}
?></
=={{header|PicoLisp}}==
<
(prinl (line) "," "SUM")
(while (split (line) ",")
(prinl (glue "," @) "," (sum format @)) ) )</
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,262 ⟶ 3,881:
=={{header|PL/I}}==
<
csv: Proc Options(Main);
/*********************************************************************
Line 3,326 ⟶ 3,945:
End;
End;</
{{in}}
<pre>
Line 3,343 ⟶ 3,962:
4,8,12,16,20,60
</pre>
=={{header|PowerShell}}==
<
@"
C1,C2,C3,C4,C5
Line 3,407 ⟶ 3,997:
## Display the object in tabular form
$records | Format-Table -AutoSize
</syntaxhighlight>
{{out}}
<pre>
Line 3,417 ⟶ 4,007:
4 8 12 16 20 60
</pre>
=={{header|Prolog}}==
Add a "SUM" column. Output is as for Lua and is not repeated here.
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.
<syntaxhighlight lang=Prolog>test :- augment('test.csv', 'test.out.csv').
% augment( +InFileName, +OutFileName)
augment(InFile, OutFile) :-
open(OutFile, write, OutStream),
( ( csv_read_file_row(InFile, Row, [line(Line)]),
% Row is of the form row( Item1, Item2, ....).
addrow(Row, Out),
csv_write_stream(OutStream, [Out], []),
fail
)
; close(OutStream)
).
% If the first item in a row is an integer, then append the sum;
% otherwise append 'SUM':
addrow( Term, NewTerm ) :-
Term =.. [F | List],
List = [X|_],
(integer(X) -> sum_list(List, Sum) ; Sum = 'SUM'),
append(List, [Sum], NewList),
NewTerm =.. [F | NewList].
</syntaxhighlight>
=={{header|PureBasic}}==
<
EnableExplicit
Line 3,471 ⟶ 4,090:
CloseConsole()
EndIf
</syntaxhighlight>
{{out|Output (in output.csv)}}
Line 3,486 ⟶ 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.
<
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
Line 3,496 ⟶ 4,115:
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')</
{{out}}
After this the data file <code>csv_data_manipulation.csv</code> gets changed from that of the task to:
Line 3,507 ⟶ 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.
<
from pathlib import Path
from tempfile import NamedTemporaryFile
Line 3,529 ⟶ 4,148:
temp_file_path = Path(temp_file.name)
temp_file_path.replace(filepath)
</syntaxhighlight>
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,538 ⟶ 4,157:
=== Using <code>pandas</code> ===
<
filepath = 'data.csv'
Line 3,545 ⟶ 4,164:
rows_sums = df.sum(axis=1)
df['SUM'] = rows_sums
df.to_csv(filepath, index=False)</
=={{header|Q}}==
<
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</
=={{header|R}}==
<syntaxhighlight lang=rsplus>
df <- read.csv(textConnection(
"C1,C2,C3,C4,C5
Line 3,561 ⟶ 4,180:
4,8,12,16,20"))
df$sum <-
write.csv(df,row.names = FALSE)
</syntaxhighlight>
{{out}}
Line 3,576 ⟶ 4,194:
This output can also be saved to a file:
<syntaxhighlight lang=R> write.csv(df, file = "foo.csv",row.names = FALSE)
</syntaxhighlight>
=={{header|Racket}}==
<
(require (planet neil/csv:1:=7) net/url)
Line 3,596 ⟶ 4,214:
(append row (list (~a (apply + xs))))))
(define (->string row) (string-join row "," #:after-last "\n"))
(string-append* (map ->string (cons head rows))))</
Example:
<
"C1, C2, C3, C4, C5
1, 5, 9, 13, 17
Line 3,605 ⟶ 4,223:
4, 8, 12, 16, 20")
(display (all-rows (open-input-string csv-file)))</
{{out}}
<pre>
Line 3,614 ⟶ 4,232:
4,8,12,16,20,60
</pre>
=={{header|Raku}}==
(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 line>my $csvfile = './whatever.csv';
my $fh = open($csvfile, :r);
my @header = $fh.get.split(',');
my @csv = map {[.split(',')]>>.Num}, $fh.lines;
close $fh;
my $out = open($csvfile, :w);
$out.say((@header,'SUM').join(','));
$out.say((@$_, [+] @$_).join(',')) for @csv;
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.)
<syntaxhighlight lang=raku line>use Text::CSV;
my $csvfile = './whatever.csv';
my @csv = Text::CSV.parse-file($csvfile);
# modify(@csv); # do whatever;
csv-write-file( @csv, :file($csvfile) );</syntaxhighlight>
=={{header|Red}}==
<
>>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"]]</
<
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)
]]</
<
>> print data
C1, C2, C3, C4, C5, SUM
Line 3,634 ⟶ 4,272:
3, 7, 11, 15, 19, 55
4, 8, 12, 16, 20, 60
>>write fileout.csv form data</
=={{header|REXX}}==
===version 1===
<
* extend in.csv to add a column containing the sum of the lines' elems
* 21.06.2013 Walter Pachl
Line 3,661 ⟶ 4,299:
Do i=1 To i-1
Call lineout csv,l.i
End</
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,674 ⟶ 4,312:
Also supported is the ability to specify the fileID of the data file to be specified.
<
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,692 ⟶ 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.*/</
{{out|output|text= to the console:}}
<pre>
Line 3,700 ⟶ 4,338:
=={{header|Ring}}==
<
# Project : CSV data manipulation
Line 3,735 ⟶ 4,373:
fclose(fpout)
see csvend + nl
</syntaxhighlight>
Output:
<pre>
Line 3,746 ⟶ 4,384:
=={{header|Ruby}}==
<
# read:
ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible.
Line 3,752 ⟶ 4,390:
# manipulate:
ar.first << "SUM"
ar[1..-1].each{|row| row << row.
# write:
CSV.open("out.csv", 'w') do |csv|
ar.each{|line| csv << line}
end</
{{output}}
<pre>c1,c2,c3,c4,c5,SUM
Line 3,766 ⟶ 4,404:
=={{header|Run BASIC}}==
<
1,5,9,13,17
2,6,10,14,18
Line 3,799 ⟶ 4,437:
cma$ = ""
print
next r</
<pre>C1,C2,C3,C4,C5
1,5,9,13,17
Line 3,817 ⟶ 4,455:
=={{header|Rust}}==
{{libheader|BurntSushi's csv crate}}
<
use std::num::ParseIntError;
use csv::{Reader, Writer};
Line 3,844 ⟶ 4,482:
writer.flush()?;
Ok(())
}</
{{output}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,853 ⟶ 4,491:
=={{header|SAS}}==
<
infile datalines dlm="," firstobs=2;
file "output.csv" dlm=",";
Line 3,867 ⟶ 4,505:
4,8,12,16,20
;
run;</
=={{header|Scala}}==
{{libheader|Scala}}
<
object parseCSV extends App {
Line 3,898 ⟶ 4,536:
*/
}</
=={{header|Seed7}}==
Line 3,904 ⟶ 4,542:
is in the same directory as the program.
<
const proc: main is func
Line 3,920 ⟶ 4,558:
writeln(join(csvData[line], ","));
end for;
end func;</
{{out}}
Line 3,930 ⟶ 4,568:
4,8,12,16,20
</pre>
=={{header|SenseTalk}}==
<syntaxhighlight lang=sensetalk>
// For test purposes, start by creating (or re-creating) the data file
put {{
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
}} into file "myData.csv"
// Read the file as a list of lists (rather than as the default list of property lists)
put CSVValue(file "myData.csv", asLists:Yes) into csvData
insert "SUM" into item 1 of csvData -- add a new column heading
// Go through all of the data rows to add the sum
repeat with rowNum= 2 to the number of items in csvData
insert the sum of item rowNum of csvData into item rowNum of csvData
end repeat
put csvData -- see the modified data as a list of lists
put CSVFormat of csvData into file "myData.csv"
put file "myData.csv" -- display the updated file contents
</syntaxhighlight>
=={{header|Sidef}}==
{{trans|
For simple files we can use the ''split'' method.
<
var csvfile = %f'data.csv';
var fh = csvfile.open_r;
Line 3,945 ⟶ 4,612:
out.say([header..., 'SUM'].join(','));
csv.each { |row| out.say([row..., row.sum].join(',')) };
out.close;</
For complex files, the ''Text::CSV'' library is recommended.
<
Hash(eol => "\n")
);
Line 3,971 ⟶ 4,638:
[header, rows...].each { |row|
csv.print(out, row);
};</
=={{header|Stata}}==
<
replace c5=c3+c4
egen sum=rowtotal(c*)
drop if mod(c3,3)==0
export delim output.csv, replace</
=={{header|Tcl}}==
{{tcllib|struct::matrix}}
{{tcllib|csv}}
<
package require csv
Line 4,011 ⟶ 4,678:
}
addSumColumn "example.csv"</
{{out|Output (in <tt>example.csv</tt>)}}
<pre>
Line 4,022 ⟶ 4,689:
Although, for this specific small task,
<
puts "[gets $f],SUM"
while { [gets $f row] > 0 } {
puts "$row,[expr [string map {, +} $row]]"
}
close $f</
suffices.
=={{header|TUSCRIPT}}==
<
$$ MODE DATA
$$ csv=*
Line 4,050 ⟶ 4,717:
csv=APPEND(csv,line)
ENDLOOP
</syntaxhighlight>
{{Out}}
<pre>
Line 4,061 ⟶ 4,728:
=={{header|TXR}}==
<
@(collect :vars (value sum))
@ (bind sum 0)
Line 4,072 ⟶ 4,739:
@ (end)
@(end)
</syntaxhighlight>
=={{header|UNIX Shell}}==
{{works with|bash}}
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,095 ⟶ 4,777:
} &&
mv "$1" "$1.bak" &&
mv "$1.new" "$1"</
{{works with|ksh}}
Line 4,103 ⟶ 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}}==
<
# csv data manipulation
#
Line 4,145 ⟶ 4,866:
for (set i 0) (< i (size lines)) (inc i)
out lines<i> endl f
end for</
=={{header|VBA}}==
Using Excel VBA to load a CSV file in a new workbook.
<
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Line 4,156 ⟶ 4,877:
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub</
=={{header|VBScript}}==
<
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,193 ⟶ 4,914:
AddElements = AddElements + CInt(arr(i))
Next
End Function</
{{In}}
Line 4,213 ⟶ 4,934:
=={{header|Vedit macro language}}==
This example adds 100 to the values in each cell at row n+1, column n.
<
for (#1 = 0; #1 < 4; #1++) {
Goto_Line(#1+2) // line (starting from line 2)
Line 4,223 ⟶ 4,944:
Num_Ins(#2+100, LEFT+NOCR) // write new value
}
File_Save_As("output.csv", OK+NOMSG) </
output.csv:
<pre>
Line 4,232 ⟶ 4,953:
4,8,12,116,20
</pre>
=={{header|Visual FoxPro}}==
<
CLOSE DATABASES ALL
SET SAFETY OFF
Line 4,245 ⟶ 4,967:
MODIFY FILE file2.csv NOEDIT IN SCREEN
SET SAFETY ON
</syntaxhighlight>
=={{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}}==
<
header:=csvFile.readln().strip(); // remove trailing "\n" and leading white space
listOfLines:=csvFile.pump(List,fcn(line){ line.strip().split(",").apply("toInt") });
Line 4,255 ⟶ 5,078:
newFile.writeln(header + ",sum");
listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(","),",",ns.sum()) });
newFile.close();</
{{out}}
<pre>
Line 4,265 ⟶ 5,088:
4,8,12,16,20,60
</pre>
[[Category:CSV]]
|