The Wayback Machine - https://web.archive.org/web/20230316070318/https://www.geeksforgeeks.org/python-program-to-read-file-word-by-word/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Python program to read file word by word

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 21 Feb, 2023
Improve Article
Save Article

Prerequisites: File Handling in Python Given a text file and the task is to read the information from file word by word in Python. Examples:

Input: I am R2J! Output: I am R2J! Input: Geeks 4 Geeks And in that dream, we were flying. Output: Geeks 4 Geeks And in that dream, we were flying.

Approach:

  1. Open a file in read mode which contains a string.
  2. Use for loop to read each line from the text file.
  3. Again use for loop to read each word from the line splitted by ‘ ‘.
  4. Display each word from each line in the text file.

Example 1: Let’s suppose the text file looks like this – Text File: read-word-by-word-python 

Python3




# 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-word 

Python3




# 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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!