Python Read a Text File Line by Line And Display Each Word Separated by a #

Hi in this article you will learn about Ram that keeps reading a text file line by line and then displays each word separated by a hash  symbol.

Let's ask the user to enter the file name and then display each word separated by a hash symbol.  

There can be two variants of the same problem so let's try to print the word separated by a space and then hash, also with the hash.

 

 

Read a Text File Line by Line And Display Each Word Separated by a #

 

 

Python Read a Text File Line by Line And Display Each Word Separated by a #

Let's take a string variable named as  file name  and ask the user to enter the file.  One is when the user enters the file name and tries to open a file in read mode and store the file descriptor.

Use the except block to catch the file not found error and print an error message and exit the program.

filename = input("Enter File Name : ")
try:
   fd = open(filename, "r")
except FileNotFoundError:
   print("File you entered does not exist")





Use the else block to read the file line by line and use another far log to split the line into words and then print the word separated by the hash

else:
   for words in fd:
       for word in words.split():
           print(f"#{word}", end="")





Complete Python Program
===========================

filename = input("Enter File Name : ")
try:
   fd = open(filename, "r")
except FileNotFoundError:
   print("File you entered does not exist")
else:
   for words in fd:
       for word in words.split():
           print(f"#{word}", end="")




Sample input file
====================

Read a Text File Line by Line And Display Each Word



Output 1
==============

#Read#a#Text#File#Line#by#Line#And#Display#Each#Word



Python Program to Separate with # and a Space
==============================================

In order to write a program that keeps reading a text file line by line and prints each word separated by a space and a hash so modify the print statement by adding a space at the end.

 

Python Read a Text File Line by Line And Display Each Word Separated by a #

 



The python program is as shown below.
================================

filename = input("Enter File Name : ")
try:
   fd = open(filename, "r")
except FileNotFoundError:
   print("File you entered does not exist")
else:
   for words in fd:
       for word in words.split():
           print(f"#{word}", end=" ")




Sample input file
================

Read a Text File Line by Line And Display Each Word



Output
=============

Enter File Name : sample.txt
#Read #a #Text #File #Line #by #Line #And #Display #Each #Word




Conclusion
================

Execute the above by python program by providing a random text file and get the word separated using a hash.

Comment it down below if you have any queries related to the above python program.

Post a Comment

0 Comments