Important Python Concept

Python Program to Read File Word by Word

We will learn about how to read a file word to word in Python language. Here, a file must be taken as an input and we have to print the words present inside the file one by one. Let us understand the above statement using the following sample input and output.

Input

  Hello everyone, this is aniket malik.

Output

  Hello 
  everyone, 
  this
  is 
  aniket
  malik.

In the above example, the line “Hello everyone, this is aniket malik.” should be stored inside a file, and by using Python language we need to read each word inside the file and print it.

Procedure

➤ Open a file in read mode.
➤ Use a for loop to read each line in the file.
➤ Use another for loop to read each word from the line.
➤ Print each word from each line.

Here, words are separated whenever whitespace is identified. Let us see the Python program to read file word to word by using the above example.

Python Program

with open('sample.txt', 'r') as file:
    for line in file:
        for word in line.split():
            print(word)

Output

Hello
everyone, 
this 
is
aniket
malik.

Explanation

with open('sample.txt', 'r') as file:  

The above line of code was used to open a file (i.e., sample.txt) in read mode and stored inside a variable name ‘file’

for line in file:

This is the first for loop, this loop is used to read each line inside the file ‘sample.txt’. The lines are temporarily stored inside the variable ‘line’.

for word in line.split():

This inner loop is used to read each word from each line in the file ‘sample.txt’. Here, each word is temporarily stored inside the variable ‘word’, and the split() function is used to split each line.

The split() method in python is used to split a string into a list of strings after breaking the given string by a specified condition.

By using a simple print statement all the words are printed.

Conclusion

We have learned about the procedure to read a file word to word, the associated Python code used to read a file word to word, and the usage of the split() function.

Aniket Malik

Aniket Malik

CERTIFIED TUTOR/TRAINER WITH 300+ REVIEWS

Facing difficulty with

this concept?