我尝试到处寻找,并没有找到一个好的答案。我正在尝试在tcl中编写嵌套的foreach循环,以从两个不同的文本文件中读取行。内部foreach循环将完全运行,但是仅在评估文件的第一行后,外部foreach循环将中断。文本文件看起来像这样(更大的除外)。
input1.txt:
1
2
3
4
5
6
7
8
9
10
input2.txt:
a
b
c
d
e
f
g
h
i
j
和我的嵌套的foreach循环是这样构造的:
# Open file 1;
set FID1 [open input1.txt r];
# Open file 2
set FID2 [open input2.txt r];
# Open an output file to check the foreach loops;
set outFID [open outputcheck.txt w];
# Nest the foreach loops to read both files
foreach PropLine [split [read $FID1] \n] {
foreach GMprop [split [read $FID2] \n] {
puts $outFID "$PropLine $GMprop";
}
}
close $FID1;
close $FID2;
close $outFID;
我的outputcheck.txt文件包含
1 a
1 b
1 c
1 d
1 e
1 f
1 g
1 h
1 i
1 j
我正在具有Windows 7操作系统的PC上通过OpenSEES.exe可执行文件运行此代码。
预先感谢您的任何见解。
如果您想对file1的每一行使用file2进行操作,则
foreach PropLine [split [read $FID1] \n] {
foreach GMprop [split [read $FID2] \n] {
puts $outFID "$PropLine $GMprop";
}
# jump back to the start of the file, so you can re-read it
# for the next iteration of the outer foreach loop
seek $FID2 0 start
}
但是,看起来就像您想配对线,所以
foreach PropLine [split [read -nonewline $FID1] \n] \
GMprop [split [read -nonewline $FID2] \n] \
{
puts $outFID "$PropLine $GMprop";
}
Tcl使您可以同时遍历多个列表,非常方便:http : //tcl.tk/man/tcl8.6/TclCmd/foreach.htm
尽管我很想逐行读取文件:
while {true} {
set status1 [gets $FID1 PropLine]
set status2 [gets $FID2 GMprop]
if {$status1 == -1 && $status2 == -1} break
puts $outFID "$PropLine $GMprop"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句