• Register
0 votes

I have a python file that contains too many lines of code.

I have written a code to count the total number of lines in a exact file (Don’t have any idea if it works).

My code:

def file_name(fname):
    with open(fname) as fn:
         for i, l in enumerate(fn):
    return i+1

Does the code give me the exact count ?

6.1k points

Please log in or register to answer this question.

1 Answer

0 votes

Can you tell me the specific version of python you are using.

To count numbers of line in code or a file for python try:

num_lines = sum(1 dor line in open('your file name'))

If you map your memory this might be best solution for you .

Try this code:

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 fn:
        for i, l in enumerate(fn):
    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))


35k points