Search code examples
pythonpython-3.xfilehandle

Hi, when i am running the below code, i am getting count as 0 , why, i expected it to show the number of lines in the file


there are 1910 lines in the file, but when i am trying to print number of lines, i am getting as 0, why? already the file handle is open, only when i am opening the file handle again after the count variable i am getting the proper value, why is this

fhandle=open('C:\\Users\\Gopi\\Documents\\Exercise Files\\mbox-short.txt','r')

for i in fhandle:
    print(i)
#counting lines in a file
count=0
#fhandle=open('C:\\Users\\Gopi\\Documents\\Exercise Files\\mbox-short.txt','r')
for j in fhandle:
    count=count+1
print('Number of lines in the file is',count)

Actual result 0 Expected result 1910


Solution

  • The first loop over the file reaches end of file and stops. The second loop picks up from where the first one stopped (i.e., EOF), so it exits immediately without ever increasing count. Add fhandle.seek(0) before the second loop to return to the beginning of the file