My question is related to file-input in Python, using open()
. I have a text file mytext.txt
with 3 lines.
I am trying to do two things with this file: print the lines, and print the number of lines.
I tried the following code:
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
Result: it prints the 3 lines correctly, but prints "number of lines: 0" (instead of 3)
I found two ways to solve it, and get it to print 3
:
1) I use one loop instead of two
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) after the first loop, I define input_file again
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
To me, it seems like the definition input_file = ...
is valid for only one looping, as if it was deleted after I use it for a loop. But I don't understand why, probably it is not 100% clear to me yet, how variable = open(filename)
treated in Python.
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…