私の質問は、を使用したPythonでのファイル入力に関連していますopen()
。mytext.txt
3行のテキストファイルがあります。私はこのファイルで2つのことをしようとしています:行を印刷することと行数を印刷することです。
次のコードを試しました。
input_file = open('mytext.txt', 'r')
count_lines = 0
for line in input_file:
print line
for line in input_file:
count_lines += 1
print 'number of lines:', count_lines
結果:3行は正しく印刷されますが、「行数:0」(3行ではなく)が印刷されます。
私はそれを解決し、それを印刷するための2つの方法を見つけました3
:
1)2つではなく1つのループを使用します
input_file = open('mytext.txt', 'r')
count_lines = 0
for line in input_file:
print line
count_lines += 1
print 'number of lines:', count_lines
2)最初のループの後、input_fileを再度定義します
input_file = open('mytext.txt', 'r')
count_lines = 0
for line in input_file:
print line
input_file = open('mytext.txt', 'r')
for line in input_file:
count_lines += 1
print 'number of lines:', count_lines
私には、定義input_file = ...
が1つのループに対してのみ有効であるように見えます。これは、ループに使用した後に削除されたかのようです。variable = open(filename)
しかし、Pythonでどのように扱われるのか、おそらくまだ100%明確ではない理由がわかりません。
By the way, I see that in this case it is better to use only one loop. However, I feel I have to get this question clear, since there might be cases when I can/must make use of it.