Python - How to get the number of lines in a text file

I would like to know if it is possible to find out how many lines the text of the file contains without using the command:

with open('test.txt') as f:
    text = f.readlines()
    size = len(text)

My file is very large, so it’s hard to use this approach ...

+7
source share
4 answers

More Pythonic will use the generator expression in the function sumas follows:

with open('test.txt') as f:
   count = sum(1 for _ in f)
+13
source

Minor modification of your approach

with open('test.txt') as f:
    line_count = 0
    for line in f:
        line_count += 1

print line_count

Notes:

Here you will go through the lines and will not load the full file into memory

+10
source

. , , . :

lines = 0
with open('test.txt') as f:
    for line in f:
        lines = lines + 1
+4
with open('test.txt') as f:
    size=len([0 for _ in f])
+4

Source: https://habr.com/ru/post/1607632/


All Articles