Topic: Count Lines in Text File Python Program
How this Program works?
- First of all we will show a message to the to enter the name of the file.
- The user will input a valid file name.
- We use input() function of Python for the above mentioned task.
- open() function will be used to open the given file in read mode, since we supply two arguments, the file name and an opening mode “r”.
- Set a line_count variable to zero.
- We will use a for loop to read and print contents of the file:
- We will read the given file line by line.
- We will count each line by adding a 1 to line_count for each iteration of the loop
- We will show the total number of lines in the text file.
Note: This is to be noted that a file with name “example.txt” must be present at d: drive. As an example we create a file with name example.txt on D: drive with the following contents, as shown in the above image:
this is example text file
this is line 2
this is last line