Python 文件'行数'读取的三种方法

Python三种文件行数读取的方法:

 

#文件比较小
count = len(open(r"d:\lines_test.txt",'rU').readlines())
print count

#文件比较大
count = -1

for count,line in enumerate(open(r"d:\lines_test.txt",'rU')):
pass
count += 1

print count

#更好的方法
count = 0

thefile = open(r"d:\lines_test.txt",'rb')

while True:
buffer = thefile.read(1024 * 8192)
if not buffer:
break
count += buffer.count('\n')
thefile.close()

print count
posted @ 2019-02-15 21:32  戒骄戒躁-沉淀积蓄  阅读(23756)  评论(0编辑  收藏  举报