python计算文件行数的方法:
1、最简单的办法是把文件读入一个大的列表中,然后统计列表的长度.如果文件的路径是以参数的形式filepath传递的,那么只用一行代码就可以完成我们的需求了:
count = len(open(filepath,'rU').readlines())
www#gaodaima.com来源gao*daima.com搞@代#码网搞代码
如果是非常大的文件,上面的方法可能很慢,甚至失效.此时,可以使用循环来处理:
<a href="https://www.gaodaima.com/tag/count" title="查看更多关于count的文章" target="_blank">count</a> = -1 for count, line in enumerate(open(thefilepath, 'rU')): pass count += 1
2、通过统计文件中换行符“
”来计算行数
count = 0 thefile = open(thefilepath, 'rb') while True: buffer = thefile.read(8192*1024) if not buffer: break count += buffer.count(' ') thefile.close( )
更多Python知识请关注搞代码网。
来源:搞代码网:原文地址:https://www.gaodaima.com