The task is to count the total number of lines in the text file.
open_file = open("demo.txt","r") count = 0 text = open_file.read() list = text.split("\n") for x in list: if x: count += 1 print("Total number of lines in the text file are:", count )
- Open the text file using open() function.
- Read the text file and split the text when “\n” is encountered and store in a list.
- Traverse through the list and increment the count variable.
- Return the count value that is the total number of lines in text file.