#!/usr/bin/tclsh
proc readCSV { channel { header 1 } { symbol , }} {
set quote 0
set data [ split [ read $channel nonewline ] "\n" ]
set line_count [ llength $data ]
puts $line_count
if { $line_count != "0" } {
for { set k 0 } { $k < $line_count } { incr k } {
set line [ lindex $data $k ]
set quote [ expr { $quote + [ regexp -all \" $line ] } ]
if { [ expr { $quote % 2 } ] == "0" } {
set quote 0
append row_temp $line
set row_temp [ split $row_temp $symbol ]
set col_count [ llength $row_temp ]
for { set i 0 } { $i < $col_count } { incr i } {
set section [ lindex $row_temp $i ]
set quote [ expr { $quote + [ regexp -all \" $section ] } ]
if { [ expr { $quote % 2 } ] == "0" } {
append cell_temp $section
if { [ regexp { "(.*)" } $cell_temp x y ] } {
set cell_temp $y
}
lappend cell $cell_temp
unset cell_temp
set quote 0
} else {
append cell_temp $section,
}
}
lappend final [ regsub -all {""} $cell \" ]
unset cell
unset row_temp
} else {
append row_temp $line\n
}
}
}
# puts $final
# generate array if needed, or return $final here
set row [ llength $final ]
set column [ llength [ lindex $final 0 ] ]
if { $header == 1 } {
for { set i 0 } { $i < $row } {incr i } {
for {set j 0 } { $j < $column } { incr j } {
set csvData([ lindex [ lindex $final 0 ] $j ],$i) [ lindex [ lindex $final $i ] $j ]
}
}
} else {
for { set i 0 } { $i < $row } { incr i } {
for { set j 0 } { $j < $column } { incr j } {
set csvData($i,$j) [ lindex [ lindex $final $i ] $j ]
}
}
}
return [ array get csvData ]
}
set csv [ open /d/frame.csv {RDWR} ]
array set csvData [ readCSV $csv ]
puts $csvData(rtpNum,1)
这个是网上学习的第一个例子。因给二维数组赋值时,数组名与(间有了空格(文中的粗体部分),调试了一个上午。开来不是所有的地方都适合用空格的!
阅读(3655) | 评论(1) | 转发(0) |