【问题标题】:TCL - Insert a row in a CSV fileTCL - 在 CSV 文件中插入一行
【发布时间】:2022-01-04 05:31:58
【问题描述】:

如果有人能帮忙,我将非常感激。

使用 Tcl 脚本,当 StringId 增加时,我想在 csv 文件中插入一行。原始数据如下:

StringId,X,Y,Z,Pit,Cutback,Dump,RoadType,Stage,Description 1,4502.99062478626,11700.2712789007,1351.70766376371,Main,m12,,坡道,, 1,4516.27744755097,11659.2215117983,1355.04407601514,Main,m12,,坡道,, 2,4573.88,11115.096,1349.655,Main,m11,,表面,, 2,4579.091,11005.027,1340.086,Main,m11,,表面,, 3,4590.818,10957.154,1335.894,Main,m11,,表面,, 3,4624.94,10868.638,1327.38,Main,m11,,表面,, 4,4672.865,10803.07,1320,Main,m11,,表面,, 4,4720.17,10757.545,1320.894,Main,m11,,Surface,,

我想通过在新行中插入 0,0,0,0 将其更改为以下内容:

StringId,X,Y,Z,Pit,Cutback,Dump,RoadType,Stage,Description 1,4502.99062478626,11700.2712789007,1351.70766376371,Main,m12,,坡道,, 1,4516.27744755097,11659.2215117983,1355.04407601514,Main,m12,,坡道,,

0,0,0,0,

2,4573.88,11115.096,1349.655,Main,m11,,Surface,, 2,4579.091,11005.027,1340.086,Main,m11,,Surface,,

0,0,0,0

3,4590.818,10957.154,1335.894,Main,m11,,Surface,, 3,4624.94,10868.638,1327.38,Main,m11,,Surface,,

0,0,0,0,

4,4672.865,10803.07,1320,Main,m11,,Surface,, 4,4720.17,10757.545,1320.894,Main,m11,,Surface,,

【问题讨论】:

  • 插入新行的标准是什么?是在stringId字段改变之后吗?

标签: csv insert tcl row edit


【解决方案1】:

在这种情况下,我们不需要完全解析文件。相反,我们可以使用lindex [split $line ","] 0 获取第一列,并将其余部分保留为未解析。唯一的另一个技巧是我们需要将列名作为它们自己的特殊事物来处理,在我们吸入其余数据之前读取它们。

set f [open $inFilename]
set columnNames [gets $f]
set data [split [read $f] "\n"]
close $f

# In theory, we should check which column is StringId with [lsearch],
# but I hard code it to 0 for convenience

set f [open $outFilename w]
puts $f $columnNames
foreach line $data {
    set id [lindex [split $line ","] 0]
    # If we've changed the current ID, print the stuff to insert
    if {[info exist current] && $current != $id} {
        puts $f "\n0,0,0,0,\n"
    }
    # Remember the current ID
    set current $id
    puts $f $line
}
close $f

【讨论】:

  • 您可能需要添加一些代码来跳过最后的空行。 [string trimright [read $f] "\n"] 会这样做。
  • 或者干脆使用[read -nonewline $f]
  • 我总是忘记那个选项!
  • @Donal Fellow 非常感谢大家。我对这个脚本不太了解,但这正是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多