如何高效地获取文件行数


本文摘自php中文网,作者anonymity,侵删。

简单的做法:

需要在python中获取大文件(数十万行)的行数。

1

2

3

4

def file_len(fname):

    with open(fname) as f:

        for i, l in enumerate(f):

            pass    return i + 1

有效的方法(缓冲区读取策略):

首先看下运行的结果:

1

2

3

4

mapcount : 0.471799945831

simplecount : 0.634400033951

bufcount : 0.468800067902

opcount : 0.602999973297

因此,对于Windows/Python2.6来说,缓冲区读取策略似乎是最快的。

以下是代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

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))

以上就是如何高效地获取文件行数的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python--dicom图像的研究

Python安装库安装失败怎么解决

用matplotlib如何绘制3d图形

Python语言支持中文吗

Python中sep是什么意思

Python编译正则表达式提高效率方法详解

Python和c先学哪个

append在Python里是什么

Python如何将数字转化为字符串

Python怎么念

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...