Home > Software engineering >  Unable to understand why a single line in my program is affecting the overall output
Unable to understand why a single line in my program is affecting the overall output

Time:10-26

I am writing a program in python that reads a file and uses the information for a certain purpose. However, my first target is to count the number of lines in my text file.

My initial program looked like this :

fhand = open("date_to_day.txt",)
n=0
date = input("Enter the day in this format 08-Jan-21 (date-month-year): ")
text = fhand.read()
for line in fhand:
    n=n 1
print("The number of lines : ",n)

and the output came out to be :

Enter the day in this format 08-Jan-21 (date-month-year): 23-Oct-21
The number of lines :  0

The output should be 365 lines but I do not know why is it zero.

However, when I change the code removing a line everything works out to be fine and the number of lines in the output is 365.:

fhand = open("date_to_day.txt",)
n=0
date = input("Enter the day in this format 08-Jan-21 (date-month-year): ")
#text = fhand.read()
for line in fhand:
    n=n 1
print("The number of lines : ",n)

My new output :

Enter the day in this format 08-Jan-21 (date-month-year): 23-Oct-21
The number of lines :  365

My text file looks :

01-Jan-21   -   Friday
02-Jan-21   -   Saturday
03-Jan-21   -   Sunday
04-Jan-21   -   Monday

The list continues by listing all the dates in the year.

CodePudding user response:

When you call fhand.read() python reads the contents of the file into memory and you are left at the end of the file with no more rows to count. If you would re-open the file again after you do read(), you should then be able to count the lines as you do.

  • Related