Exercise 65

Write an algorithm in python in the form of a function which takes as argument the path of an existing file and returns the number of lines of this file.


def numberOfLines( file):

# opening the file in read mod
f = open(file , 'r')

# getting the list of lines
listLines = f.readlines()

# The number of lines is n = len(listLines)
return len(listLines)
# Testing the function
# we must of beginning create a file for example myFile.txt which contains:
line number 1
line number 2
line number 3
line number 4
line number 5
print("Number of lines of myFile.txt is : " , numberOfLines("myFile.txt"))
# The output is : Number of lines of myFile.txt is : 5

Younes Derfoufi

Leave a Reply