677
In this example we will show how to get the line count of a file
Example
The test file contains the following, notice the blank lines
this is line 1 this is line 2 this is another line line to count and another line
Open the file in read-only mode.
We then use a for loop, iterate through the object named f.
In each iteration, a line is read an we increase the value of variable after each iteration.
def linecount(filename): with open(filename) as f: for i, l in enumerate(f): pass return i + 1 print(linecount("linecount.txt"))
When you run this you will see something like this
>>> %Run linecount.py 7