Program to read file word by word using Python

by | Aug 1, 2021 | Python Programs

Home » Python » Python Programs » 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.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

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

Author