CSV data manipulation: Difference between revisions

 
(10 intermediate revisions by 6 users not shown)
Line 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>
 
Line 1,162 ⟶ 1,261:
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}}==
<syntaxhighlight lang=scheme>
Line 1,800 ⟶ 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}}==
Line 2,154 ⟶ 2,341:
 
=={{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===
<syntaxhighlight lang=java>import java.io.*;
Line 2,833 ⟶ 3,116:
4,8,12,16,20,60
"</syntaxhighlight>
 
=={{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}}==
Line 4,651 ⟶ 4,971:
=={{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=ecmascript"wren">import "io" for File
 
var lines = File.read("rc.csv").split("\n").map { |w| w.trim() }.toList