![图片[1]-python中怎样求行数?-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5ec24a48e1091224.jpg)
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()原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容