Reputation: 951
I'm trying to write some data to a CSV file from TCL script with the set fid [open temp.csv a]
'a' the append command. I see all the data gets appended from the next row. But i want my new set of data to be added to the next column instead. How can i do this case???
set fid [open temp.csv a]
foreach line $data {
if { [regexp "SUM" $line == 1] } {
incr line_counter
if { [expr {$line_counter % 2}] == 0} {
if {[regexp {(MBytes) +([0-9\.]*)} $line match pre tput]==1 } {
puts $fid " $line_counter Throughput: $tput Mbps"
}
}
}
}
close $fid
set fid [open temp.csv r]
while {[gets $fid chars] >= 0} {
puts $chars
}
close $fid
Upvotes: 1
Views: 2707
Reputation: 137717
To add a column to a CSV file, you have to add data to each line of that CSV file (or at least the lines that have data you care about). This requires rewriting the file completely, as you can't insert data in a general text file (CSV is a specialization of that) without rewriting all the subsequent lines of the file. Append mode is definitely going to be wrong for that.
Try using the CSV package in Tcllib. In particular, read the CSV file into a matrix, add a column to that matrix, and then serialize the matrix back out again as CSV.
Upvotes: 2
Reputation: 5365
There is a CSV package already in TCL, so why reinvent the wheel? http://tcllib.sourceforge.net/doc/csv.html
Upvotes: 0
Reputation: 55533
That "a" flag in the open
command means "open file in append mode", that is, create the file if it does not exist otherwise do not discard its contents and just position the "stream pointer" to the end of the file so that the next call to puts
on that file descriptor would append the data to the file.
Hence probably your problem is that you do not understand that general file manipulation commands never interpret the data in a file1: it's just an opaque stream of bytes to them; any interpretation of the data has to be preformed elsewhere. That's where the concepts of serialization and deserialization appear.
I think you should look at the specialized csv package from tcllib.
1 Well, file streams can interpret the contents of their files to some extent to make it easier working with text files: you can specify the behaviour of an opened file channel with regard to character encoding and line breaks.
Upvotes: 2