Topic: Count Words in Text File Python Program
Python Count Words in Text File
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 word_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.
- Each line is split into words
- The words of that line are counted and added to the total word count of the file.
- We will show the total number of words 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
706 total views, 1 views today