我看到一些以前的帖子与打开文件以执行读写操作有关但我无法得到我的任务的答案.我想将一些结果附加到一个文件(如果它不存在,应该创建一个新文件).
但是,如果文件已经有结果,则应跳过追加并继续下一次搜索下一个结果.我为此编写了一个脚本,我在阅读文件时遇到了问题.脚本是这样的:
proc example {} {
set a [result1 result2 ... result n]
set op [open "sample_file" "a+"]
set file_content ""
while { ![eof $op] } {
gets $op line
lappend file_content $line
}
foreach result $a {
if {[lsearch $file_content $result] == -1} {
puts $op $result
}
}
close $op
}
Run Code Online (Sandbox Code Playgroud)
注意:在这个脚本中,我发现变量"line"为空{""}.我想我在阅读文件时遇到了麻烦.请在这件事上给予我帮助
你忘了,是在阅读之前寻找文件的开头:
proc example {} {
set a {result1 result2 ... result n}; # <== curly braces, not square
set op [open "sample_file" "a+"]
set file_content ""
seek $op 0; # <== need to do this because of a+ mode
while { ![eof $op] } {
gets $op line
lappend file_content $line
}
foreach result $a {
if {[lsearch $file_content $result] == -1} {
puts $op $result
}
}
close $op
}
Run Code Online (Sandbox Code Playgroud)
您可以使用一个读取语句简化读取(while循环和所有):
proc example {} {
set a {result1 result2 result3}
set op [open "sample_file" "a+"]
seek $op 0
set file_content [read $op]
foreach result $a {
if {[lsearch $file_content $result] == -1} {
puts $op $result
}
}
close $op
}
example
Run Code Online (Sandbox Code Playgroud)