嗨,当我 运行 下面的代码时,我被计数为 0 ,为什么,我希望它显示文件中的行数

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

文件中有 1910 行,但是当我尝试打印行数时,我得到的是 0,为什么?文件句柄已经打开,只有当我在 count 变量之后再次打开文件句柄时我才得到正确的值,为什么是这样

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)

实际结果0 预期结果 1910

文件的第一个循环到达文件末尾并停止。第二个循环从第一个循环停止的地方(即 EOF)开始,因此它立即退出而不会增加 count。 在第二个循环之前添加fhandle.seek(0)到return到文件的开头

文件指针总是指向文件的开头,并在每次循环迭代时向结尾移动,即向 EOF 移动。您需要使用单个循环进行计数,或者您需要再次将文件指针设置为文件的开头。

fhandler.seek(0,0)