Learn how to write Python script which can read through a file and provide number of lines in it. The lines within the file can be counted in different ways. You can plainly count based on ‘\n’ (end of line) or based on regular expression which matches specific string.

You can edit the below python code using IDLE editor and save it as *.py script.

fhand = open(‘abc.txt’)
numberoflines = 0
for line in fhand:
if line.startswith(’22/09/2015 ‘):
numberoflines = numberoflines + 1;

print numberoflines

Code Details-

fhand = open(‘abc.txt’)  — This will create a file object and assign it to fhand. By default the file will open in read mode.

numberoflines = 0 — variable to hold count of lines
for line in fhand:  — For loop to parse through the file content line by line till end of file.
if line.startswith(’22/09/2015 ‘): — Checks whether the line is starting with specific string value.

numberoflines = numberoflines + 1; – – Increases the count if the string is found.

print numberoflines  — prints the count of line where string is found.


Code to find count of lines for all the files within a folder

import os
import re
lines = 0
for filename in os.listdir(os.getcwd()):
fhand = open(filename);
for line in fhand:
if re.search(“.*/09/2015 “,line):
lines = lines + 1;

print lines

You can try different ways and make changes to this code to achieve the same result.