Using file handling concepts, we can read the contents written in a file using the read () method present in Python. For reading, we can open the file using 'r' mode and then read the contents.
Algorithm:
- Step 1: Open the file in 'r' mode for reading.
- Step 2: Use the read file to read file contents.
- Step 3: Increment the count if a new line is encountered.
- Step 4: Print the file content and the print the line count.
- Step 5: Close the file.
Program to count the number of lines in a file
File : drinks.dat
Output:
In the above code, we have seen the counting of lines read from a file in Python. For that we have first opened a file using the open() method using 'r' mode. Then we initialize a variable count to count the number of lines in the file. Then we have used the read() method to read the file contents byte by byte. If a line break '\n' is encountered, increase the count otherwise do nothing. Print it and read the next byte. And at the end print the total count of lines in the file.
need an explanation for this answer? contact us directly to get an explanation for this answer