Open In App

Python program to read file word by word

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word.

Read file word by word

In this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a better understanding.

Example 1:

Let's suppose the text file looks like this - Text File read-word-by-word-pythonCode Explanation:

Open a file in read mode that contains a string then use a for loop to read each line from the text file again use for loop to read each word from the line split by ' '.Display each word from each line in the text file.

Python
# Python program to read 
# file word by word
 
# opening the text file
with open('GFG.txt','r') as file:
 
    # reading each line    
    for line in file:
 
        # reading each word        
        for word in line.split():
 
            # displaying the words           
            print(word) 

Output:

Geeks
4
geeks

Time Complexity: O(n), where n is the total number of words in the file.
Auxiliary Space: O(1), as the program is reading and displaying each word one by one without storing any additional data.

Example 2:

Let's suppose the text file contains more than one line. Text file.python-read-word-by-wordCode Explanation: Open a file in read mode that contains a string then use a for loop to read each line from the text file again use for loop to read each word from the line split by ' '.Display each word from each line in the text file.

Python
# Python program to read 
# file word by word
 
# opening the text file
with open('GFG.txt','r') as file:
 
    # reading each line    
    for line in file:
 
        # reading each word        
        for word in line.split():
 
            # displaying the words           
            print(word) 

Output:

Geeks
4
Geeks
And
in
that
dream,
we
were
flying.

Time complexity: O(n), where n is the total number of words in the file.
Auxiliary space: O(1), as only a constant amount of extra space is used to store each word temporarily while printing it.

For more please read this article: Read and writing text file


Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy