繁体   English   中英

TCL-将行从文本文件提取到TCL脚本

[英]TCL - Extract line from text file to TCL Script

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

  • 我有一个文本文件 (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行)?

非常感谢 !

您打开该文件以进行读取,但实际上并未从中读取文件。 $ 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

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 

这将接二连三地进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM