Вот проблема. У меня есть файл names.txt. Содержимое этого файла выглядит следующим образом. Вопрос просит отобразить номера имен в этом файле. Я мог бы сделать с пока цикл. Работает, без проблем. Но по какой-то причине, если бы я хотел сделать это с циклом для , это выдает мне неправильное количество имен.
Julia Roberts
Michael Scott
Kevin Malone
Jim Halpert
Pam Halpert
Dwight Schrute
Это цикл while. Работает отлично.
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()
Консоль дает мне правильный ответ.
There are 6 names in the names.txt file.
А это мой проблемный цикл
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()
И это вывод.
There are 3.0 names in the names.txt file.
Там должно быть 6 имен, а не 3 имени .:
Что может отсутствовать в этом коде чтения файла? Заранее спасибо.