python中怎样求行数?
发布时间:2026-03-18 22:12:32

计算python文件行数的方法:
1、最简单的方法是将文件读入一个大列表,然后统计列表的长度。如果文件的路径以参数的形式通过filepath传输,我们的需求只能通过一行代码来完成:
count=len(open(filepath,'rU').readlines())
如果是一个非常大的文件,上述方法可能非常缓慢,甚至无效。此时,循环可用于处理:
count=-1 forcount,lineinenumerate(open(thefilepath,'rU')): pass count+=1
2、通过统计文件中的换行符n计算行数
count=0
thefile=open(thefilepath,'rb')
whileTrue:
buffer=thefile.read(8192*1024)
ifnotbuffer:
break
count+=buffer.count('\n')
thefile.close()请关注Python自学网了解更多Python知识。
下一篇 python中怎样退出程序运行?
