« »
2008-08-21Python

150

Python:统计文件行数

Pyhont食谱里的,链接:http://wiki.woodpecker.org.cn/moin/PyCkBk-4-7

添加了一个方法4,同时发现我的电脑上第三种方法要快一些
D:\\python\>countLines.py
linecount_1 49238
linecount_2 49238
linecount_3 49238
linecount_4 49238
linecount_1: 0.18
linecount_2: 0.16
linecount_3: 0.09
linecount_4: 0.16

  1. # -*- coding: utf-8 -*-
  2. import time
  3.  
  4. def timeo(fun, n=10):
  5.     start = time.clock()
  6.     for i in range(n): fun()
  7.     stend = time.clock()
  8.     thetime = stend-start
  9.     return fun.__name__, thetime                        #返回函数名称,函数运行10次总时间的 元组
  10.  
  11. import os
  12.  
  13. fname="YourFileName" #稍微改了一下,添加了一个文件名变量
  14.  
  15. def linecount_wc():
  16.     return int(os.popen('wc -l nuc').read().split()[0]) #使用外部系统程序 wc -l
  17.  
  18. def linecount_1( ):                                      #使用方法1
  19.     return len(open(fname).readlines())
  20.  
  21. def linecount_2():                                      #使用方法2
  22.     count = 0
  23.     for line in open(fname).xreadlines(): count += 1
  24.     return count
  25.  
  26. def linecount_3():                                      #使用方法3
  27.     count = 0
  28.     thefile = open(fname)
  29.     while 1:
  30.         buffer = thefile.read(65536)
  31.         if not buffer: break
  32.         count += buffer.count('\n')
  33.     return count
  34.  
  35. def linecount_4():   #添加的方法4
  36.     count=0
  37.     for line in open(fname):
  38.         #if(line!='\n'): count+=1
  39.         count+=1
  40.     return count
  41.  
  42. for f in linecount_1, linecount_2, linecount_3,linecount_4:
  43.     print f.__name__, f()
  44.  
  45. for f in linecount_1, linecount_2, linecount_3,linecount_4:
  46.     print "%s: %.2f"%timeo(f)

您还可能感兴趣的内容

日志信息 »

该日志于2008-08-21 16:16由 x72 发表在Python分类下, 你可以发表评论。除了可以将这个日志以保留源地址及作者的情况下引用到你的网站或博客,还可以通过RSS 2.0订阅这个日志的所有评论。

没有评论

发表评论 »


返回顶部