In: Computer Science
On Python
Write a function that accepts a relative file path as parameter and returns number of non-empty lines in the file. Test your function with the provided sample file studentdata.txt.
This question can be solved in two ways:
Way 1. If a line with spaces is considered empty
Way 2. If a line with spaces is not considered empty
I'll solve this question in both ways:
Way 1:
def countNonEmptyLines(path): #Required Function
fl = open(path,"r")
lines = fl.readlines()
count = 0
for line in lines:
#Checking if the line is empty or not
#strip() returns true on encountering spaces
if(line and line.strip()):
count = count + 1
return count
nonEmptyLines = countNonEmptyLines("./studentdata.txt")
#The lines with just spaces are also considered as empty
print("The number of non empty lines in the given file are: " + str(nonEmptyLines))
Way 2:
def countNonEmptyLines(path): #Required Function
fl = open(path,"r")
lines = fl.readlines()
count = 0
for line in lines:
#Checking if the line is empty or not
if(line):
count = count + 1
return count
nonEmptyLines = countNonEmptyLines("./studentdata.txt")
#The lines with just spaces are not considered as empty
print("The number of non empty lines in the given file are: " + str(nonEmptyLines))