0

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

Gopi B
  • 21
  • 6
  • 1
    Try putting both the `print(i)` and the `count=count+1` in the same loop – Carsten Aug 01 '19 at 10:55
  • 1
    Possible duplicate of [How to get line count cheaply in Python?](https://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python) – sahasrara62 Aug 01 '19 at 11:07

2 Answers2

5

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

GPhilo
  • 18,519
  • 9
  • 63
  • 89
0

file pointer always points to beginning of file, and moves towards the end everytime the loop iterates, i.e towards EOF. You need to use a single loop for counting, or you need to set file pointer to the beginning of the file again.

fhandler.seek(0,0)