[英]TCL - Extract line from text file to TCL Script
好吧,我試圖在網上找到我的答案,但實際上我沒有,我真的需要幫助。
C:/Users/00_file/toto.odb, dis,455, stre,54, stra,25, C:/Users/00_file/tota.odb,
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.