如何以最有效的内存和时间方式获取大文件的行数?

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

当前回答

下面这句话怎么样:

file_length = len(open('myfile.txt','r').read().split('\n'))

用这种方法在一个3900行的文件上计时只需要0.003秒

def c():
  import time
  s = time.time()
  file_length = len(open('myfile.txt','r').read().split('\n'))
  print time.time() - s

其他回答

我发现你可以。

f = open("data.txt")
linecout = len(f.readlines())

会给你答案吗

这段代码更短、更清晰。这可能是最好的方法:

num_lines = open('yourfile.ext').read().count('\n')
def line_count(path):
    count = 0
    with open(path) as lines:
        for count, l in enumerate(lines, start=1):
            pass
    return count

计数= max(开放(文件))[0]

大文件的另一种选择是使用xreadlines():

count = 0
for line in open(thefilepath).xreadlines(  ): count += 1

对于Python 3,请参阅:在Python 3中什么替代xreadlines() ?