Program to read file word by word using Python

Introduction

The task is to open a file and read all the words of that file.

Program to read file word by word using Python

Program

with open('demo.txt','r') as txtfile:   

#Reading lines of file     

    for readline in txtfile: 

#Read and print the words        

        for str in readline.split():           

            print(str)

Output

Program to read file word by word using Python Output

Explanation

Approach:

  • To open a file in python, in-built function open() is used, it takes two arguments: the file name or path and mode (i.e. ‘r’ for read, ‘w’ for write etc).
  • Read the lines of file and words using for loop and print the words.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.