【问题标题】:TCL - Extract line from text file to TCL ScriptTCL - 从文本文件中提取行到 TCL 脚本
【发布时间】:2018-03-15 14:17:34
【问题描述】:

好吧,我试图在网上找到我的答案,但实际上我没有,我真的需要帮助..

  • 我有一个文本文件 (file.txt),其中包含:
 C:/Users/00_file/toto.odb,
 dis,455,
 stre,54,
 stra,25,
 C:/Users/00_file/tota.odb,
  • 还有一个 TCL 脚本,允许我读取每一行的
set Infile [open "C:/Users/00_file/file.txt" r]
set filelines [split $Infile ","] 
set Namepath [lindex $filelines 1 0]   #*doesn't work*
set dis [lindex $filelines 2 0]        # *work good*
...

问题是当我想用我的 TCL 脚本完整的文本文件的第 1 行时,一些信息丢失并且额外的字符消失了..

如何获得完整的字符串(文本文件的第 1 行)?

非常感谢!

【问题讨论】:

  • 你能不能。改善你的问题? 1) file.txt 恰好包含多行,但您使用 split 会破坏由逗号 (",") 分隔的内容,而不是换行符 ("\n")。 2)你的措辞中的“完整行”是什么?您至少应该以符合您期望的方式记录file.txt 的摘录(实际上不是您所看到的)。

标签: text input tcl extract


【解决方案1】:

您打开文件进行读取,但实际上并未从中读取。 $Infile 只是(基本上)一个指向文件描述符的指针,而不是文件的内容:

% set fh [open file.txt r]
% puts $fh
file3

从文件中读取的惯用方式:逐行

set fh [open "C:/Users/00_file/file.txt" r]
set data [list]
while {[get $fh line] != -1} {
    lappend data [split $line ,]
}
close $fh

或者,读取整个文件并将其拆分为换行符

set fh [open "C:/Users/00_file/file.txt" r]
set data [lmap line [split [read -nonewline $fh] \n] {split $line ,}]
close $fh

然后访问数据

set Namepath [lindex $data 0 0]   ;# first line, first field 
set dis [lindex $data 1 1]        ;# second line, second field

【讨论】:

    【解决方案2】:

    Tcl 代码如下:

     		set file [open c:/filename.txt ]
        set file_device [read  $file]
        set data [split $file_device "\n"]
    
        for {set count 0} {$count < 2} {incr count} {
            
        puts $data
            
            # for every iterartion one line will be printed.
        	# split /n is use for getting the end of each line.
            # open command open the file at given path. 
            # read command is use to read the open file.
        }
        close $file
        break

    这将一个接一个地进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 2011-11-13
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多