Tcl / Tk写在特定行 [英] Tcl/Tk write in a specific line
问题描述
我想在Textdocument中写一行,但是我的代码有问题,我不知道错误在哪里。
I want to write in a specific line in Textdocument but there´s a Problem with my code, i don´t know where the bug is.
set fp [open C:/Users/user/Desktop/tst/settings.txt w]
set count 0
while {[gets $fp line]!=-1} {
incr count
if {$count==28} {
break
}
}
puts $fp "TEST"
close $fp
文件仅包含TEST。
有人有想法吗?
The File only contains TEST. Has anybody an idea?
推荐答案
您正在使用 w作为访问参数,该文件将截断文件。因此,您在打开文件时会丢失文件中的所有数据。进一步了解打开命令
You are using 'w' as access argument, which truncates the file. So you will loose all data from file while opening. Read more about open command
您可以使用'r +'或'a +'。
You can use 'r+' or 'a+'.
也可以在特定行之后写,您可以将指针移至所需位置。
Also To write after a particular line you can move the pointer to the desired location.
set fp [open C:/Users/user/Desktop/tst/settings.txt r+]
set count 0
while {[gets $fp line]!=-1} {
incr count
if {$count==28} {
break
}
set offset [tell $fp]
}
seek $fp $offset
puts $fp "TEST"
close $fp
要替换完整的行,将可以通过以下方式轻松完成。重写所有行并将新数据写入所需的行。
To replace a complete line it would be easier to do in following way. Rewrite all the lines and write new data on the desired line.
set fp [open C:/Users/user/Desktop/tst/settings.txt r+]
set count 0
set data [read $fp]
seek $fp 0
foreach line [split $data \n] {
incr count
if {$count==28} {
puts $fp "TEST"
} else {
puts $fp $line
}
}
close $fp
这篇关于Tcl / Tk写在特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!