我正在研究一些简单的示例,但我遇到了这个示例,但无法弄清楚为什么我没有获得 loop2 的预期结果。循环 1 是我用来逐行查看正在发生的事情的循环。奇怪的是在第 1875 行,startswith 返回 true(见循环 1),但它没有在循环 2 中打印。
显然我遗漏了一些重要的东西。请帮我看看。
文本文件位于:http://www.py4inf.com/code/mbox-short.txt
xfile = open("SampleTextData.txt", 'r')
cntr = 0
print("Loop 1 with STEPWISE PRINT STATEMENTS")
for line in xfile:
cntr = cntr + 1
if cntr >1873 and cntr < 1876:
print(line)
print(line.startswith('From: '))
line = line.rstrip()
print(line)
print(cntr)
print()
print("LOOP 2")
for line in xfile:
line = line.rstrip()
if line.startswith('From: '):
print(line)
请您参考如下方法:
xfile 等文件对象是单遍迭代器。要遍历文件两次,您必须关闭并重新打开文件,或者使用 seek 返回到文件的开头:
xfile.seek(0)
只有这样,第二个循环才会遍历文件的行。
