Search code examples
pythonpython-3.xprogramming-languages

Why is my program not reading the first line of code in the referenced file(fileName)?


def main():
    read()

def read():

    fileName=input("Enter the file you want to count: ")

    infile=open(fileName , "r")
    text=infile.readline()
    count=0
    while text != "":

        text=str(count)     
        count+=1
        text=infile.readline()



        print(str(count)+ ": " + text)

    infile.close()     
main()

-the referenced .txt file has only two elements

44

33

-the output of this code should look like

1: 44

2: 33

-my output is

1: 33

2:

im not sure why the program is not picking up the first line in the referenced .txt file. The line numbers are correct however 33 should be second to 44.


Solution

  • The reason is explained in the comments:

    def main():
        read()
    
    def read():
        fileName=input("Enter the file you want to count: ")
        infile=open(fileName , "r")
        text=infile.readline()  ##Reading the first line here but not printing
        count=0
        while text != "":
          text=str(count)     
          count+=1
          text=infile.readline() ##Reading the 2nd line here
          print(str(count)+ ": " + text) ##Printing the 2nd line here, missed the first 
                                         ##line
    
        infile.close()     
    
    
    main()
    

    Modify the program as:

    def main():
       read()
    
    def read():
       fileName= input("Enter the file you want to count: ")
       infile = open(fileName , "r")
       text = infile.readline()
       count = 1                             # Set count to 1
       while text != "":
          print(str(count)+ ": " + str(text))   # Print 1st line here
          count = count + 1                     # Increment count to 2 
          text = infile.readline()              # Read 2nd line 
    
       infile.close()                           # Close the file
    
    
    main()