首頁 >後端開發 >Python教學 >如何有效率地取得文件行數

如何有效率地取得文件行數

anonymity
anonymity原創
2019-05-25 10:46:022783瀏覽

簡單的做法:

需要在python中取得大檔案(數十萬行)的行數。

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass    return i + 1

如何有效率地取得文件行數

有效的方法(緩衝區讀取策略):

首先看下運行的結果:

mapcount : 0.471799945831
simplecount : 0.634400033951
bufcount : 0.468800067902
opcount : 0.602999973297

因此,對於Windows/Python2.6來說,緩衝區讀取策略似乎是最快的。

以下是程式碼:

from __future__ import with_statement
import time
import mmap
import random
from collections import defaultdict
def mapcount(filename):
    f = open(filename, "r+")
    buf = mmap.mmap(f.fileno(), 0)
    lines = 0
    readline = buf.readline
    while readline():
        lines += 1
    return lines
def simplecount(filename):
    lines = 0
    for line in open(filename):
        lines += 1
    return lines
def 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 lines
def opcount(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
counts = 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))

以上是如何有效率地取得文件行數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn