Python program to read file word by word

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Geeks
4
geeks

Example 2: Let’s suppose the text file contains more than one line.

Text file:

python-read-word-by-word

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.