CSV data manipulation: Difference between revisions
m
syntax highlighting fixup automation
(Added XPL0 example.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 27:
=={{header|11l}}==
<
I L.index == 0
line ‘’= ‘,SUM’
E
line ‘’= ‘,’sum(line.split(‘,’).map(Int))
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 306:
=={{header|Arturo}}==
<
;
; C1,C2,C3,C4,C5
Line 328:
prints pad column 6
print ""
]</
=={{header|AutoHotkey}}==
<
{
i := A_Index
Line 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 347:
=={{header|AWK}}==
adds a column sum to a csv table
<
BEGIN { FS = OFS = "," }
NR==1 {
Line 359:
}
print $0, sum
}</
<pre>awk -f csv_data_manipulation.awk data.csv
C1,C2,C3,C4,C5,SUM
Line 369:
=={{header|BaCon}}==
Load the data, change a value and add a column with totals. Then save and print.
<
OPTION DELIM ","
Line 388:
SAVE total$ TO "data.csv"
PRINT total$
</syntaxhighlight>
<pre>
C1,C2,C3,C4,C5,SUM
Line 403:
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
<
OPEN "manip2.csv" FOR OUTPUT AS #2
Line 416:
CLOSE #1, #2
END</
{{out}}
<pre>
Line 423:
=={{header|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"⟩
Line 432:
sums ← ⟨"SUMS"⟩ ∾+´˘ 1↓ intdata
done ← sums ∾˜˘ intdata
</syntaxhighlight>
=={{header|C}}==
<syntaxhighlight lang=c>
#define TITLE "CSV data manipulation"
Line 712:
return 0;
}
</syntaxhighlight>
{{out|Output (in <tt>tmp/csv-data-manipulation.result.csv</tt>)}}
<pre>
Line 723:
=={{header|C sharp|C#}}==
<
using System.Linq;
Line 744:
}
}
</syntaxhighlight>
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 755:
=={{header|C++}}==
<
#include <vector>
#include <iostream>
Line 883:
oCSV.save( "test_out.csv" );
return 0;
}</
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 894:
=={{header|Clojure}}==
<
(require '[clojure.data.csv :as csv]
'[clojure.java.io :as io])
Line 909:
(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 923:
Using tech.ml.dataset
<
(require '[tech.v3.dataset :as ds]
'[tech.v3.datatype.functional :as dfn])
Line 934:
(ds/write! (add-sum (ds/->dataset "resources/input.csv")) "resources/output.csv")
</syntaxhighlight>
=={{header|COBOL}}==
<
IDENTIFICATION DIVISION.
PROGRAM-ID. CSV.
Line 1,031:
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 1,076:
result-header (nested-list-to-csv data-list ",")))))
(main)
</syntaxhighlight>
{{out|Output (in <code>results.txt</code>)}}
Line 1,088:
=={{header|D}}==
<
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
Line 1,097:
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 1,109:
{{libheader| System.Types}}
{{Trans|C#}}
<
program CSV_data_manipulation;
Line 1,155:
end;
TFile.WriteAllLines(FILENAME, Input);
end.</
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 1,163:
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 1,185:
</syntaxhighlight>
{{out}}
<
(define file.csv #<<
C1,C2,C3,C4,C5
Line 1,203:
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 1,226:
MyNewDataset := PROJECT(MyDataset,Appended(LEFT));
OUTPUT(myNewDataset,,'~Rosetta::myNewCSVFile',CSV,OVERWRITE);</
{{Out}} (contents of Rosetta::myNewCSVFile):
<pre>C1x,C2y,C3z,C4a,C5b
Line 1,235:
=={{header|Elixir}}==
<
defmodule Csv do
defstruct header: "", data: "", separator: ","
Line 1,287:
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
</syntaxhighlight>
{{Out}}
Line 1,299:
=={{header|Erlang}}==
<
-module( csv_data ).
Line 1,336:
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
</syntaxhighlight>
{{out}}
Line 1,349:
=={{header|Euphoria}}==
<
--- with trace
-- trace(0)
Line 1,440:
main()
</syntaxhighlight>
{{out}}
Line 1,453:
=={{header|F_Sharp|F#}}==
<
[<EntryPoint>]
Line 1,467:
File.WriteAllLines ("test_out.csv", output)
0
</syntaxhighlight>
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 1,479:
=={{header|Factor}}==
The <code>csv</code> vocabulary provides words for working with csv files, strings, and streams.
<
IN: rosetta-code.csv-manipulation
Line 1,488:
[ 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,500:
=={{header|Forth}}==
<
\ USAGE:
\ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv
Line 1,548:
THEN
2DROP 2DROP
;</
{{out}}
<pre>
Line 1,561:
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,667:
array(p) = line(k:n)
end subroutine
end program</
=== Old Fortran ===
Line 1,680:
Another F90 feature is the SUM function that adds the elements of an array span. Even though for the example the first column looks rather like a record number, all five columns will be added, but otherwise the statement would be SUM(X(2:N)). Other modifications can be made without much difficulty, if desired. The output format is I0 rather than say I2, as it provides only the needed number of characters to present the integer's value. There is no corresponding F format code, and free-format output would roll out many spaces as padding in case of large numbers, that are not present here. It would be needed for a more general solution, but for this example, I0 will do.
<
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,701:
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,712:
=={{header|FreeBASIC}}==
<
Open "manip.csv" For Input As #1 ' existing CSV file
Line 1,731:
Close #1
Close #2</
{{out}}
Line 1,745:
=={{header|FunL}}==
<
data Table( header, rows )
Line 1,789:
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,802:
=={{header|Gambas}}==
<
Dim sData As String = File.Load("data.csv")
Dim sLine, sTemp As String
Line 1,833:
File.Save(User.home &/ "CSVData.csv", sData)
End</
Output:
<pre>
Line 1,844:
=={{header|Go}}==
<
import (
Line 1,901:
log.Fatal(err)
}
}</
{{in|sample.csv}}
<pre>
Line 1,920:
=={{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,927:
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')</
csv_out.txt:
Line 1,940:
Array-based solution:
<
import Data.List (intercalate)
import Control.Monad (when)
Line 1,984:
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 2,036:
\2, 6, 10, 14, 18\n\
\3, 7, 11, 15, 19\n\
\4, 8, 12, 16, 20"</
Examples:
Line 2,090:
3. Construction and combination
<
where sums = map (show . sum) (read <$$> drop 1 (values sample))</
<pre>λ> sampleSum
Line 2,104:
This version only works in Unicon, but can be easily adapted to work in Icon.
<
procedure main(A)
Line 2,114:
write(encodeCSV(csv))
}
end</
Sample run:
Line 2,131:
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}}==
===Roll Your Own===
<
import java.awt.Point;
import java.util.HashMap;
Line 2,258:
}
}
}</
{{out|Output (in <tt>test_out.csv</tt>)}}
<pre>
Line 2,270:
{{libheader|Apache commons-csv}}
Using the [http://commons.apache.org/proper/commons-csv/ Apache commons-csv] library.
<
import java.util.*;
Line 2,395:
}
}
</syntaxhighlight>
{{in}} data/csvtest_in.csv
<pre>
Line 2,414:
===uniVocity-parsers===
Using the [http://www.univocity.com/pages/parsers-tutorial uniVocity-parsers] library.
<
public static void main(String[] args) throws IOException {
Line 2,446:
writer.writeRows(new ArrayList<List<Object>>());
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 2,454:
As an embedded scripting language which evolved in browsers carefully isolated from local file systems, JavaScript has no standard file IO libraries. The readFile() and writeFile() functions used in this example are written for JS embedded in macOS as 'JavaScript for Automation'. Other embeddings will require other definitions of these functions, and in some JS contexts it will not be possible to write them at all.
<
'use strict';
Line 2,529:
);
})();</
{{Out}}
Line 2,543:
Below is a toy example to add new columns to an CSV file. Other manipulations, i.e. adding new rows, modifying existing values and so forth, can be accomplished very easily.
<
// formats for the data parameter in the function below: {col1: array | function, col2: array | function}
Line 2,583:
return idx;
}
});</
{{output}}
Line 2,599:
The writing out of each line is facilitated by jq's @csv builtin. We must "slurp in" the file (using the -s option) so the header line can be handled specially.
<
def read_csv:
split("\n")
Line 2,613:
([]; ($line|map(tonumber)) as $line | . + [$line + [$line|add]]))[] ] ;
read_csv | add_column("SUM") | map(@csv)[]</
{{Out}}
$ jq -s -R -r -f CSV_data_manipulation.jq input.csv
Line 2,623:
=={{header|Julia}}==
<
ifn = "csv_data_manipulation_in.dat"
Line 2,631:
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
</
<pre>
$ cat csv_data_manipulation_out.dat
Line 2,642:
=={{header|Kotlin}}==
<
import java.io.File
Line 2,655:
File("example2.csv").writeText(text) // write to new file
println(text) // print to console
}</
{{out}}
Line 2,667:
=={{header|Lingo}}==
<
-- Simplified CSV parser (without escape character support etc.).
-- First line is interrepted as header with column names.
Line 2,765:
delete char (str.length-delim.length+1) to str.length of str
return str
end</
<
eol = numtochar(10)
Line 2,810:
3,7,11,15,19,55
4,8,12,16,20,60
"</
=={{header|Lua}}==
Adds a SUM column.
<
for line in io.lines('file.csv') do
table.insert(csv, {})
Line 2,845:
local file=io.open('file.csv', 'w')
file:write(newFileData)
</syntaxhighlight>
{{out}}
Line 2,856:
=={{header|M2000 Interpreter}}==
<
Module Checkit {
Function Sum {
Line 2,904:
}
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,938:
> ExportMatrix("data_out.csv",M,target=csv);
96
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica's Import and Export functions support CSV files.
<
->{{"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];</
{{out}}
<pre>(C1 C2 C3 C4 C5 Sum
Line 2,959:
=={{header|MATLAB}} / {{header|Octave}}==
=== Using file manipulation ===
<
fid = fopen(filename);
header = fgetl(fid);
Line 2,971:
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 '~'
<
sum = 0
Line 2,998:
end for
write</
=={{header|NetRexx}}==
Line 3,004:
{{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 3,126:
end
return lineOut
</syntaxhighlight>
{{in}} data/csvtest_in.csv
<pre>
Line 3,148:
Nim's standard library contains a robust CSV parser, but for this simple document that's not necessary.
<
let
Line 3,172:
outf.writeLine(line)
inc lineNumber</
{{out}}
Line 3,186:
Objeck has a CSV parser with built-in functions.
<
use Data.CSV;
Line 3,218:
}
}
</syntaxhighlight>
{{out}}
Line 3,234:
Using the '''csv''' module available in '''Opam''':
<
List.rev (this :: (List.rev lst))
Line 3,252:
) data
in
Csv.output_all (Csv.to_channel stdout) (fields :: sums)</
{{out}}
Line 3,271:
{{Works with|PARI/GP|2.7.4 and above}}
<
\\ CSV data manipulation
\\ 10/24/16 aev
Line 3,290:
\\ Testing:
processCsv("c:\\pariData\\test");
</syntaxhighlight>
{{in}} data/test.csv file
Line 3,311:
{{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,357:
ts.Free;
end.
</syntaxhighlight>
{{in}} input.csv file
Line 3,377:
=={{header|Perl}}==
For simple files, you can use [http://p3rl.org/split split]:
<
use warnings;
use strict;
Line 3,415:
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,442:
# 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.
<!--<
<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;">"""
Line 3,476:
<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>
<!--</
{{out}}
<pre>
Line 3,488:
=={{header|PHP}}==
<
<?php
Line 3,524:
$row++;
}
?></
=={{header|PicoLisp}}==
<
(prinl (line) "," "SUM")
(while (split (line) ",")
(prinl (glue "," @) "," (sum format @)) ) )</
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,539:
=={{header|PL/I}}==
<
csv: Proc Options(Main);
/*********************************************************************
Line 3,603:
End;
End;</
{{in}}
<pre>
Line 3,622:
=={{header|PowerShell}}==
<
@"
C1,C2,C3,C4,C5
Line 3,655:
## Display the object in tabular form
$records | Format-Table -AutoSize
</syntaxhighlight>
{{out}}
<pre>
Line 3,671:
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.
<
% augment( +InFileName, +OutFileName)
Line 3,693:
append(List, [Sum], NewList),
NewTerm =.. [F | NewList].
</syntaxhighlight>
=={{header|PureBasic}}==
<
EnableExplicit
Line 3,748:
CloseConsole()
EndIf
</syntaxhighlight>
{{out|Output (in output.csv)}}
Line 3,763:
=== 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,773:
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,784:
=== 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,806:
temp_file_path = Path(temp_file.name)
temp_file_path.replace(filepath)
</syntaxhighlight>
{{Out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,815:
=== Using <code>pandas</code> ===
<
filepath = 'data.csv'
Line 3,822:
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}}==
<
df <- read.csv(textConnection(
"C1,C2,C3,C4,C5
Line 3,840:
df$sum <- rowSums(df)
write.csv(df,row.names = FALSE)
</syntaxhighlight>
{{out}}
Line 3,852:
This output can also be saved to a file:
<
</syntaxhighlight>
=={{header|Racket}}==
<
(require (planet neil/csv:1:=7) net/url)
Line 3,872:
(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,881:
4, 8, 12, 16, 20")
(display (all-rows (open-input-string csv-file)))</
{{out}}
<pre>
Line 3,894:
(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
my $fh = open($csvfile, :r);
my @header = $fh.get.split(',');
Line 3,903:
$out.say((@header,'SUM').join(','));
$out.say((@$_, [+] @$_).join(',')) for @csv;
close $out;</
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
my $csvfile = './whatever.csv';
my @csv = Text::CSV.parse-file($csvfile);
# modify(@csv); # do whatever;
csv-write-file( @csv, :file($csvfile) );</
=={{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,930:
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,957:
Do i=1 To i-1
Call lineout csv,l.i
End</
{{out}}
<pre>C1,C2,C3,C4,C5,SUM
Line 3,970:
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,988:
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,996:
=={{header|Ring}}==
<
# Project : CSV data manipulation
Line 4,031:
fclose(fpout)
see csvend + nl
</syntaxhighlight>
Output:
<pre>
Line 4,042:
=={{header|Ruby}}==
<
# read:
ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible.
Line 4,053:
CSV.open("out.csv", 'w') do |csv|
ar.each{|line| csv << line}
end</
{{output}}
<pre>c1,c2,c3,c4,c5,SUM
Line 4,062:
=={{header|Run BASIC}}==
<
1,5,9,13,17
2,6,10,14,18
Line 4,095:
cma$ = ""
print
next r</
<pre>C1,C2,C3,C4,C5
1,5,9,13,17
Line 4,113:
=={{header|Rust}}==
{{libheader|BurntSushi's csv crate}}
<
use std::num::ParseIntError;
use csv::{Reader, Writer};
Line 4,140:
writer.flush()?;
Ok(())
}</
{{output}}
<pre>C1,C2,C3,C4,C5,SUM
Line 4,149:
=={{header|SAS}}==
<
infile datalines dlm="," firstobs=2;
file "output.csv" dlm=",";
Line 4,163:
4,8,12,16,20
;
run;</
=={{header|Scala}}==
{{libheader|Scala}}
<
object parseCSV extends App {
Line 4,194:
*/
}</
=={{header|Seed7}}==
Line 4,200:
is in the same directory as the program.
<
const proc: main is func
Line 4,216:
writeln(join(csvData[line], ","));
end for;
end func;</
{{out}}
Line 4,228:
=={{header|SenseTalk}}==
<
// For test purposes, start by creating (or re-creating) the data file
put {{
Line 4,254:
put file "myData.csv" -- display the updated file contents
</syntaxhighlight>
=={{header|Sidef}}==
{{trans|Raku}}
For simple files we can use the ''split'' method.
<
var csvfile = %f'data.csv';
var fh = csvfile.open_r;
Line 4,270:
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 4,296:
[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,336:
}
addSumColumn "example.csv"</
{{out|Output (in <tt>example.csv</tt>)}}
<pre>
Line 4,347:
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,375:
csv=APPEND(csv,line)
ENDLOOP
</syntaxhighlight>
{{Out}}
<pre>
Line 4,386:
=={{header|TXR}}==
<
@(collect :vars (value sum))
@ (bind sum 0)
Line 4,397:
@ (end)
@(end)
</syntaxhighlight>
=={{header|UNIX Shell}}==
Line 4,403:
Very simple solution using powerfull and ancient but strong linux command, I named "tr" and "bc", and internal variable bash test capabilities :
<syntaxhighlight lang=text>cat csv | while read S; do
[ -z ${S##*C*} ] && echo $S,SUM || echo $S,`echo $S | tr ',' '+' | bc`
done</
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</
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,435:
} &&
mv "$1" "$1.bak" &&
mv "$1.new" "$1"</
{{works with|ksh}}
Line 4,446:
{{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
Line 4,481:
close a : close b : end ' close files and terminate
</syntaxhighlight>
=={{header|Ursa}}==
<
# csv data manipulation
#
Line 4,524:
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,535:
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,572:
AddElements = AddElements + CInt(arr(i))
Next
End Function</
{{In}}
Line 4,592:
=={{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,602:
Num_Ins(#2+100, LEFT+NOCR) // write new value
}
File_Save_As("output.csv", OK+NOMSG) </
output.csv:
<pre>
Line 4,613:
=={{header|Visual FoxPro}}==
<
CLOSE DATABASES ALL
SET SAFETY OFF
Line 4,625:
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.
<
var lines = File.read("rc.csv").split("\n").map { |w| w.trim() }.toList
Line 4,642:
}
}
file.close()</
{{out}}
Line 4,659:
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
<
def LF=$0A, EOF=$1A;
int Val, Char;
Line 4,698:
CrLf(0);
];
]</
{{out}}
Line 4,711:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<
open #2, "manip2.csv", "w" //new CSV file for writing changed data
Line 4,726:
close #1
close #2
end</
=={{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,736:
newFile.writeln(header + ",sum");
listOfLines.pump(newFile.writeln,fcn(ns){ String(ns.concat(","),",",ns.sum()) });
newFile.close();</
{{out}}
<pre>
|