您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何高效地获取文件行数

2024/3/17 15:29:20发布23次查看
简单的做法:
需要在python中获取大文件(数十万行)的行数。
def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1
有效的方法(缓冲区读取策略):
首先看下运行的结果:
mapcount : 0.471799945831simplecount : 0.634400033951bufcount : 0.468800067902opcount : 0.602999973297
因此,对于windows/python2.6来说,缓冲区读取策略似乎是最快的。
以下是代码:
from __future__ import with_statementimport timeimport mmapimport randomfrom collections import defaultdictdef mapcount(filename): f = open(filename, "r+") buf = mmap.mmap(f.fileno(), 0) lines = 0 readline = buf.readline while readline(): lines += 1 return linesdef simplecount(filename): lines = 0 for line in open(filename): lines += 1 return linesdef bufcount(filename): f = open(filename) lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return linesdef opcount(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1counts = defaultdict(list)for i in range(5): for func in [mapcount, simplecount, bufcount, opcount]: start_time = time.time() assert func("big_file.txt") == 1209138 counts[func].append(time.time() - start_time)for key, vals in counts.items(): print key.__name__, ":", sum(vals) / float(len(vals))
以上就是如何高效地获取文件行数的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product