2016-04-26 48 views
0

作爲標題:使用for循環打印文件的每一行後,我無法用另一個for循環打印文件。Python open()函數:使用for循環後無法正常打印文件

for循環是否更改pos變量?

pos = open('nnn.txt','r') 
print pos 
count = 0 
for line in pos: 
    line = line.rstrip() 
    if line.startswith('Hey'): 
     print line 
     count += 1 
print count 

count = 0 
print line 
for lines in pos: 
    lines = lines.rstrip() 
    print lines 
    count += 1 
print count 

the content of the file

cmd

回答

3

[是否] for循環變更POS變量?

是的。對文件進行迭代會將「指針」移動到文件末尾,因此無法再讀取它。

您可以使用pos.seek(0)將指針重置爲開頭。然後你可以再讀一遍。