CSV data manipulation: Difference between revisions
no edit summary
No edit summary |
|||
Line 1,899:
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}}
<pre>
[[File:CSV_Manipulation.png]]
</pre>
=={{header|Gambas}}==
|