Python program to read file word by word
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:
- Open a file in read mode which contains a string.
- Use
for
loop to read each line from the text file. - Again use
for
loop to read each word from the line splitted by ‘ ‘. - Display each word from each line in the text file.
Example 1: Let’s suppose the text file looks like this –
Text File:
# 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
Example 2: Let’s suppose the text file contains more than one line.
Text file:
# 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.
Last Updated on November 1, 2021 by admin