2016-04-26 9 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)を使用して、ポインタを先頭にリセットできます。それからもう一度読むことができます。

関連する問題