Here is the problem. I have names.txt file. The contents of this file as follows. The question asks to display to numbers of names in this file. I could do with while loop. It works, no problem. But for some reason, if I wanted to do this with for loop it gives me wrong number of names.
Julia Roberts
Michael Scott
Kevin Malone
Jim Halpert
Pam Halpert
Dwight Schrute
This is the while loop. It runs perfect.
def main():
try:
# open the names.txt file in read mode.
infile=open("names.txt", "r")
# set an accumulator for number of names
numbers_of_name=0.0
# read the first line
line=infile.readline()
# read the rest of the file
while line!="":
numbers_of_name+=1
line=infile.readline()
# print the numbers of names in the names.txt file.
print("There are", int(numbers_of_name), "names in the names.txt file.")
# close the file
infile.close()
except IOError as err:
print (err)
# call the main function
main()
The console gives me correct answer.
There are 6 names in the names.txt file.
And this is my problematic for loop
def main():
try:
# open the names.txt file in read mode.
infile=open("names.txt", "r")
# set an accumulator for number of names
numbers_of_name=0.0
# read the rest of the file
for line in infile:
line=infile.readline()
numbers_of_name+=1
# print the numbers of names in the names.txt file.
print("There are ", numbers_of_name, "names in the names.txt file.")
# close the file
infile.close()
except IOError as err:
print (err)
# call the main function
main()
And this is the output.
There are 3.0 names in the names.txt file.
There should be 6 names not 3 names.:
What might be missing part in this file reading code? Thanks in advance.