Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

it's possible to determine how many lines exist in file without per line iteration? [duplicate]

Possible Duplicate:
How to get line count cheaply in Python?

Good day. i have some code below, which implements per line file reading and counter iteration.

def __set_quantity_filled_lines_in_file(self):
    count = 0
    with open(self.filename, 'r') as f:
        for line in f:
             count += 1
    return count

My question is, are there methods to determine how many lines of text data in current file without per line iteration?

Thanks!

like image 621
Dmitry Zagorulkin Avatar asked Dec 28 '22 01:12

Dmitry Zagorulkin


1 Answers

In general it's not possible to do better than reading every character in the file and counting newline characters.

It may be possible if you know details about the internal structure of the file. For example, if the file is 1024kB long, and every line is 1kB in length, then you can deduce there are 1024 lines in the file.

like image 64
Li-aung Yip Avatar answered Jan 31 '23 06:01

Li-aung Yip