python 嵌套 'for' 循环中断得太早
python nested 'for' loop breaks too soon
我看不出这个嵌套循环发生了什么。内部(for line in temp:)循环运行良好,但外部 for 循环(for cnt in range)仅运行一次,因此 temp 仅附加到 infile 一次。
with open("temp_inv.ext") as temp:
with open(infile, 'a') as of:
for cnt in range(1, sample_cnt):
for line in temp:
l = None
if "INVERSE_MODELING" in line:
l = line.replace(smp_num[0], smp_num[cnt])
if "solutions" in line:
l = line.replace(smp_num[0], smp_num[cnt])
if "netpath" in line:
l = line.replace(smp_num[0], smp_num[cnt])
if l is None:
of.write(line)
else: of.write(l)
我已经检查过 'sample_cnt' 是一个整数并且 'smp_num' 是一个有效的数组。
我错过了什么?
编辑:
为想要使用类似方法的其他人澄清 -
我想通过更改基于 'smp_num' 数组的字符串,在修改 'temp' 之后将 'temp' 附加到 'of'。添加 {temp.seek(0)} 解决了我的问题,我错过了外循环仍在 {with} 语句内,因此需要再次在 运行 之前寻找。
您需要在阅读完所有行后使用 seek() 来倒回文件。使用
temp.seek(0)
在外循环的某处
我看不出这个嵌套循环发生了什么。内部(for line in temp:)循环运行良好,但外部 for 循环(for cnt in range)仅运行一次,因此 temp 仅附加到 infile 一次。
with open("temp_inv.ext") as temp:
with open(infile, 'a') as of:
for cnt in range(1, sample_cnt):
for line in temp:
l = None
if "INVERSE_MODELING" in line:
l = line.replace(smp_num[0], smp_num[cnt])
if "solutions" in line:
l = line.replace(smp_num[0], smp_num[cnt])
if "netpath" in line:
l = line.replace(smp_num[0], smp_num[cnt])
if l is None:
of.write(line)
else: of.write(l)
我已经检查过 'sample_cnt' 是一个整数并且 'smp_num' 是一个有效的数组。
我错过了什么?
编辑:
为想要使用类似方法的其他人澄清 -
我想通过更改基于 'smp_num' 数组的字符串,在修改 'temp' 之后将 'temp' 附加到 'of'。添加 {temp.seek(0)} 解决了我的问题,我错过了外循环仍在 {with} 语句内,因此需要再次在 运行 之前寻找。
您需要在阅读完所有行后使用 seek() 来倒回文件。使用
temp.seek(0)
在外循环的某处