1.小文件处理方式
count = len(open(filepath,'r').readlines())
#如果是非常大的文件,上面的方法可能很慢,甚至失效
2.文件过大处理方式
1.推荐使用,查找速度挺快
def file_count1(file_path):
import time
t_start = time.time()
count = 0
f = open(file_path, 'rb')
while True:
buffer = f.read(8192*1024)
if not buffer:
break
count += buffer.count(b'\n')
f.close()
return count,time.time() - t_start
# (829995, 0.06681966781616211) 测试所用时间
2.推荐使用,代码简洁
def file_count2(file_path):
import time
t_start = time.time()
for count, line in enumerate(open(file_path, 'r',encoding='utf-8'),start=1):
pass
# print(count)
# count += 1
return count,time.time() - t_start
#(829995, 0.3650527000427246) 测试所用时间