CSV data manipulation: Difference between revisions

 
(8 intermediate revisions by 6 users not shown)
Line 742:
Range for test [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];
/* cargamos el array todocon DOUBLEdetección de enteros como LONG */
test = Load_matrix_mt( pSDS(test), "load_matrix.txt", dataFile, DET_LONG);
/* modifica algunas cosas del archivo */
/* sChg() test,no 0,1es necesario aquí, "Columnaporque 1");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;
Line 1,256 ⟶ 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,894 ⟶ 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,248 ⟶ 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,927 ⟶ 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,745 ⟶ 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