You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Python程序中一条读取文件的语句会导致行数统计结果为0

问题原因

这是Python文件读取时的文件指针偏移导致的问题:

  • 调用fhand.read()方法时,会一次性读取文件的全部内容,同时文件指针会直接移动到文件的末尾位置
  • 后续你再用for line in fhand遍历文件对象时,是从当前指针位置(文件末尾)开始读的,自然读不到任何内容,所以计数结果为0
  • 当你注释掉fhand.read()这一行时,文件指针始终停留在文件开头,遍历可以读到所有行,计数就正常了

解决方案

如果你后续确实需要用到读取到的全文内容text,可以用以下两种方法解决:

方法1:重置文件指针到开头

在读完内容后调用fhand.seek(0)把指针移回文件起始位置,再遍历统计行数:

fhand = open("date_to_day.txt",)
n=0
date = input("Enter the day in this format 08-Jan-21 (date-month-year): ")
text = fhand.read()
# 重置文件指针到开头
fhand.seek(0)
for line in fhand:
    n=n+1
print("The number of lines : ",n)

方法2:直接从已经读取的全文内容统计行数

不需要再二次遍历文件对象,直接统计换行符数量即可,性能更高:

fhand = open("date_to_day.txt",)
date = input("Enter the day in this format 08-Jan-21 (date-month-year): ")
text = fhand.read()
# 直接从读取的全文统计行数
n = text.count('\n')
# 若文件最后一行没有换行符,需要额外+1,可根据你的文件实际情况调整
if not text.endswith('\n'):
    n += 1
print("The number of lines : ",n)

额外优化建议

Python中操作文件更推荐使用with上下文管理器,会自动帮你关闭文件,避免资源泄露:

with open("date_to_day.txt") as fhand:
    text = fhand.read()
n = text.count('\n') + (0 if text.endswith('\n') else 1)
print("The number of lines : ",n)

内容的提问来源于stack exchange,提问作者Akash Arjun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:54:03