Home » Read a file word by word in python

Read a file word by word in python

1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course

In this code example we show how to read a file word by word and display the contents

The process is as follows

Open a file in read mode which contains text.
Use a for loop to read each line from the text file.
Use another for loop to read each word from the line split by ‘ ‘.
Display each word from each line in the text file.

Table of Contents

Example 1

In this example we read in a text file called testfile.txt

The contents are as follows

this is a test file

# Read a file word by word
# open the text file
with open('testfile.txt','r') as file:
    # read each line    
    for line in file:
        # read each word        
        for word in line.split():
            # display the words           
            print(word) 

This will display the following

>>> %Run readfile1.py
this
is
a
test
file

Example 2

In this example we read in a text file called testfile2.txt which has more than one line of text

The contents are as follows

this is a test file
this is line 2

# Read a file word by word
# open the text file
with open('testfile2.txt','r') as file:
    # read each line    
    for line in file:
        # read each word        
        for word in line.split():
            # display the words           
            print(word) 

This will display the following

>>> %Run readfile1.py
this
is
a
test
file
this
is
line
2

Link

This is in github

https://github.com/programmershelp/maxpython/tree/main/code%20example/file%20operations

readfile1 and the 2 text files called testfile and testfile2

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More