Editor

Python Program to Read a Text File and Separate Words with #

Beginner · File handling · CBSE class 12 practical list

This program reads a text file line by line and prints the words of each line followed by a # symbol, so the line "Python is fun" is shown as Python#is#fun#. It is one of the first programs in the CBSE class 12 practical file and uses the two basic text file skills: reading a file one line at a time and splitting a line into words.

Program

file_words_separated_by_hash.py
# Make a sample file to work on (in your practical file, this file already exists)
with open("story.txt", "w") as f:
f.write("Python is easy to learn\n")
f.write("Files keep data after the program ends\n")
f.write("Practice makes a programmer perfect\n")
print("Words separated by #:")
with open("story.txt", "r") as f:
for line in f:
words = line.split() # split the line into a list of words
for word in words:
print(word, end="#") # print the word, then # instead of a new line
print() # move to the next output line
Output
Words separated by #:
Python#is#easy#to#learn#
Files#keep#data#after#the#program#ends#
Practice#makes#a#programmer#perfect#

How it works

  1. The program first writes three lines to story.txt, so it has a file to read.
  2. Opening the file with with open("story.txt", "r") as f closes it automatically when the block ends.
  3. for line in f reads the file one line at a time.
  4. line.split() breaks the line into words wherever there are spaces, and it also drops the newline at the end of the line.
  5. print(word, end="#") prints each word followed by # instead of a new line, and the empty print() ends the output line once all its words are printed.

Another way to write it

Using join (no # after the last word)

Using join (no # after the last word)
# Make a sample file to work on (in your practical file, this file already exists)
with open("story.txt", "w") as f:
f.write("Python is easy to learn\n")
f.write("Files keep data after the program ends\n")
with open("story.txt", "r") as f:
for line in f:
print("#".join(line.split()))
Output
Python#is#easy#to#learn
Files#keep#data#after#the#program#ends

"#".join(words) puts # only between the words, so each line ends without a trailing #. Use whichever form your teacher expects.

Try it yourself

Change end="#" to end=" | " and run the program again to see how end controls what is printed after each word.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises