Tcl使用csv写一个文件

时间:2017-09-21 22:48:35

标签: csv tcl

我需要帮助编写一个tcl,它从csv文件中读取部分数据并以下列模式写入文本文件。

NAME : FROM= -100 -346 -249 -125 TO= -346 -249 -125 100 COLOR= COLOR1 COLOR2 COLOR3 COLOR4

NAME将是一个固定的行,

应该从csv文件和

中检索

FROM和TO信息

COLOR信息可以是来自Tcl本身的硬编​​码颜色数组。

从下面的csv数据中,MIN下的第一个值(-100)将是文本文件FROM下的第一个值(-100)。 excel MAX列的最后一个值(100)将是文本文件TO列下的最后一个值(100)。 excel中VALUE列下的值将被舍入,并用作显示的每个模式的TO和FROM。

Data    VALUE   
100 -345.8756   
200 -249.3654   
300 -125.3554   
COUNT   MIN MAX
1   -100    -98
93  84  86
98  94  96
99  96  98
100 98  100

enter image description here

2 个答案:

答案 0 :(得分:0)

一些指示:

  • reading lines from a file
  • 使用set fields [regexp -inline -all {\S+} $line]将行拆分为由任意空格分隔的单词
  • 你需要保留一些布尔标志作为状态机,以确定如何处理当前行(你是在收集值还是寻找最小值/最大值)
  • 使用[expr {round([lindex $fields end])}]来舍入值:请参阅https://tcl.tk/man/tcl8.6/TclCmd/expr.htm#M22

看看是否能让你入门。

答案 1 :(得分:0)

package require struct::matrix
package require csv
package require fileutil

array set OPTS { 
    csv_input_filename    output/stackoverflow.csv 
    txt_output_filename   output/stackoverflow.txt
    colors                {COLOR1 COLOR2 COLOR3 COLOR4}
}

set output_format {NAME : 
FROM= %s %s %s %s
TO= %s %s %s %s
COLOR= %s
}

try {::struct::matrix xdata} on error {} {xdata destroy; ::struct::matrix xdata}
set chan [open $OPTS(csv_input_filename)]
csv::read2matrix $chan xdata , auto
close $chan
csv::joinlist [xdata get rect 0 0 end end]

fileutil::writeFile $OPTS(txt_output_filename) \
 [format $output_format [xdata get cell 1 5] \
 [expr {round([xdata get cell 1 1])}] [expr {round([xdata get cell 1 2])}] \
 [expr {round([xdata get cell 1 3])}] [expr {round([xdata get cell 1 1])}] \
 [expr {round([xdata get cell 1 2])}] [expr {round([xdata get cell 1 3])}] \
 [xdata get cell 2 9] [list {*}$OPTS(colors)]]
xdata destroy

fileutil::cat [file native $OPTS(txt_output_filename)]
# NAME :
# FROM= -100 -346 -249 -125
# TO= -346 -249 -125 100
# COLOR= COLOR1 COLOR2 COLOR3 COLOR4

注意:

脚本应该产生预期的输出 .txt 文件,当然假设 .csv 文件包含在当前运行目录中的输出子文件夹中。

假设脚本文件名为“matrix_csv_extract.tcl”,您只需交互地获取 tcl 脚本以使其运行:

source matrix_csv_extract.tcl
相关问题