增量文件名 TCL
Increment file name TCL
我的输入文件有 5 行,所有 5 行都打印到 1 个文件中。如何在放置期间打印一个文件中的每一行?如何增加现有文件名?
# Input file
1 2 3 4
1 3 4 5
2 3 4 5
1 2 3 4
set infile [open "infile.txt" r]
set outfile [open "outfile.txt" w]
set count 0
while {[gets $infile line] > 0} {
incr count
puts $outfile"$count" "I want to split the input file into 4 different files. Each file is one line"
}
TCL好像不喜欢上面的语法?我希望得到 outfile1, outfile2.....
当你这样做时:
set outfile [open "outfile.txt" w]
文件句柄 outfile
已创建,与 'outfile.txt' 相关联,已打开以供写入。此文件句柄将与打开的文件保持关联,直到它
已关闭。如果你想输出到不同的文件,你必须打开另一个
文件并将文件句柄分配给变量。
为了您的问题,您需要打开输出文件
在 while
循环中。
如果您打算写入不同的文件,文件名应该不同。这就是 $count
要去的地方。在您当前的代码中,$outfile
不是文件,而是文件的 channel identifier。
例如,您可以做的是:
set infile [open "infile.txt" r]
set count 0
while {[gets $infile line] > 0} {
incr count
set outfile [open "outfile$count.txt" w]
puts $outfile $line
close $outfile
}
close $infile
这将创建文件 outfile1.txt
.. outfile5.txt
.
我的输入文件有 5 行,所有 5 行都打印到 1 个文件中。如何在放置期间打印一个文件中的每一行?如何增加现有文件名?
# Input file
1 2 3 4
1 3 4 5
2 3 4 5
1 2 3 4
set infile [open "infile.txt" r]
set outfile [open "outfile.txt" w]
set count 0
while {[gets $infile line] > 0} {
incr count
puts $outfile"$count" "I want to split the input file into 4 different files. Each file is one line"
}
TCL好像不喜欢上面的语法?我希望得到 outfile1, outfile2.....
当你这样做时:
set outfile [open "outfile.txt" w]
文件句柄 outfile
已创建,与 'outfile.txt' 相关联,已打开以供写入。此文件句柄将与打开的文件保持关联,直到它
已关闭。如果你想输出到不同的文件,你必须打开另一个
文件并将文件句柄分配给变量。
为了您的问题,您需要打开输出文件
在 while
循环中。
如果您打算写入不同的文件,文件名应该不同。这就是 $count
要去的地方。在您当前的代码中,$outfile
不是文件,而是文件的 channel identifier。
例如,您可以做的是:
set infile [open "infile.txt" r]
set count 0
while {[gets $infile line] > 0} {
incr count
set outfile [open "outfile$count.txt" w]
puts $outfile $line
close $outfile
}
close $infile
这将创建文件 outfile1.txt
.. outfile5.txt
.