This is a Python Program to count the number of words in a text file.
The program takes the file name from the user and counts number of words in that file.
1. Take the file name from the user.
2. Read each line from the file and split the line to form a list of words.
3. Find the length of items in the list and print it.
Here is source code of the Python Program to count the number of words in a text file. The program output is also shown below.
fname = input("Enter file name: ") num_words = 0 with open(fname, 'r') as f: for line in f: words = line.split() num_words += len(words) print("Number of words:") print(num_words)
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. The number of words in each line is counted using len() and the count variable is incremented.
6. The number of words in the file is printed.
Case 1: Contents of file: Hello world Output: Enter file name: data1.txt Number of words: 2 Case 2: Contents of file: This programming language is Python Output: Enter file name: data2.txt Number of words: 5
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.