【问题标题】: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嗨,当我运行以下代码时,我的计数为 0,为什么,我希望它显示文件中的行数
【发布时间】:2019-08-01 10:53:56
【问题描述】:

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

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

【问题讨论】:

标签: python python-3.x filehandle


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    fhandler.seek(0,0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 2018-12-09
      • 1970-01-01
      相关资源
      最近更新 更多