How to get the number of lines in a text file using python ?

Published: April 08, 2020

Tags: python;

DMCA.com Protection Status

Examples of how to get the number of lines in a text file using python:

Table of contents

Example 1

First example using readlines() and len():

>>> f = open('data.txt', 'r')
>>> text=f.readlines()
>>> NumberOfLine = len(text)
>>> NumberOfLine
10

Example 2

A second example using a loop for:

f = open('data.txt', 'r')

NumberOfLine = 0
for line in f:
    NumberOfLine += 1

print 'Nombre de lignes: ',NumberOfLine

Note: when you reach the end of the file, we can use the function seek(0) to restart at the first line:

f.seek(0)

References