在TCL中写入文件
我有以下代码,但我的report1.out只有k变量的最后一个值。如何更改它,使其写入k的值,然后写入新行和新值 我会感激你的帮助 代码是:在TCL中写入文件,tcl,Tcl,我有以下代码,但我的report1.out只有k变量的最后一个值。如何更改它,使其写入k的值,然后写入新行和新值 我会感激你的帮助 代码是: #创建一个过程 过程测试{}{ 设定43 b组27 集合c[expr$a+b] 集合e[expr fmod($a,$b)] 集合d[expr[expr$a-$b]*$c] 放置“c=$CD=$DE=$e” 对于{set k 0}{$k
#创建一个过程
过程测试{}{
设定43
b组27
集合c[expr$a+b]
集合e[expr fmod($a,$b)]
集合d[expr[expr$a-$b]*$c]
放置“c=$CD=$DE=$e”
对于{set k 0}{$k<10}{incr k}{
设置输出管1[打开“报告1.输出”w+]
放入$outfile1“k=$k”
关闭$outfile1
如果{$k<5}{
放置“k=$k<5,pow=[expr pow($d,$k)]”
}否则{
放入“k=$k>=5,mod=[expr$d%$k]”
}
}
}
#调用过程
测试
您正在使用w+
作为文件的打开模式。以下是Tcl的open
命令手册页的一部分:
r Open the file for reading only; the file must already exist. This is the
default value if access is not specified.
r+ Open the file for both reading and writing; the file must already exist.
w Open the file for writing only. Truncate it if it exists. If it does not
exist, create a new file.
w+ Open the file for reading and writing. Truncate it if it exists. If it
does not exist, create a new file.
a Open the file for writing only. If the file does not exist, create a new empty
file. Set the file pointer to the end of the file prior to each write.
a+ Open the file for reading and writing. If the file does not exist, create a
new empty file. Set the initial access position to the end of the file.
因此,w+
会截断文件(如果存在),这就是为什么只得到一行输出。您应该改用a+
,或者干脆使用a
,因为您实际上不需要读取文件
或者,您可以重写代码,使文件在循环之外只打开一次:
set outfile1 [open "report1.out" w+]
for {set k 0} {$k < 10} {incr k} {
puts $outfile1 "k= $k"
if {$k < 5} {
puts "k= $k k < 5, pow = [expr pow ($d, $k)]"
} else {
puts "k= $k k >= 5, mod = [expr $d % $k]"
}
}
close $outfile1
set outfile1[打开“report1.out”w+]
对于{set k 0}{$k<10}{incr k}{
放入$outfile1“k=$k”
如果{$k<5}{
放置“k=$k<5,pow=[expr pow($d,$k)]”
}否则{
放入“k=$k>=5,mod=[expr$d%$k]”
}
}
关闭$outfile1
这还可以通过避免重复打开/关闭文件来提高效率。@user3035037很高兴它有所帮助。你应该投票并接受答案,以表明它解决了你的问题!我还有一个问题。如果我想在k旁边添加另一个变量,比如说y,这样我的文本文件看起来像ek=0y=3和新行,依此类推。。。。我将如何做到这一点。如果on可以回答,我们将不胜感激。@user3035037如果没有更多的上下文,很难回答。也许你可以用更多的细节开始一个新的问题,而不是用这种方式评论。
set outfile1 [open "report1.out" w+]
for {set k 0} {$k < 10} {incr k} {
puts $outfile1 "k= $k"
if {$k < 5} {
puts "k= $k k < 5, pow = [expr pow ($d, $k)]"
} else {
puts "k= $k k >= 5, mod = [expr $d % $k]"
}
}
close $outfile1