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
Links | Site |
---|---|
readlines() | python doc |
len() | python doc |
how to count the total number of lines in a text file using python | stackoverflow |
How to get line count cheaply in Python? | stackoverflow |
Count number of lines in a txt file with Python - but exclude blank lines | stackoverflow |