首页 > 解决方案 > 创建具有正确索引的文件

问题描述

我目前有一个包含 300 行和 3 列的文本文件。

我需要遍历所有行,用 3 列中的值分配 3 个变量。

每次循环通过 for 循环时,我都需要生成一个输出文件,其索引号在输出文件的名称中。(也就是说,我总共需要产生300个输出文件)

例如,对于第 49 次迭代,我需要生成一个名为product-49.out的输出文件。你对如何做到这一点有什么建议吗?

标签: outputtcl

解决方案


这是一个如何做到这一点的例子:

set counter 1
set fp_in [open my-text-file.txt r]
set line [gets $fp_in]
while { ![eof $fp_in] } {
  # store the columns on the current line in variables:
  lassign $line var1 var2 var3
  set fp_out [open "product-$counter.out" w]
  # write one line from the input file to each output file:
  puts $fp_out $line
  close $fp_out
  set line [gets $fp_in]
  incr counter
}
close $fp_in

推荐阅读