ByteBoard Notes Notes

Read a text file line by line and display each word separated by #

Computer Science XII · Experiment 06 of 29 · Python

★ CBSE suggested12-CSPython programs
Expt. No.06
Page No.12

Words separated by #

Aim

To write a Python program that reads a text file line by line and displays each word separated by a #.

Concepts used

Algorithm

  1. Open the file in read mode.
  2. Read all lines into a list with readlines().
  3. For each line, split it into words.
  4. Join the words with "#" and display the result.

Program

# Display the words of a text file separated by # def show_words(filename):    with open(filename, "r") as f:        lines = f.readlines()    for line in lines:        words = line.split()        print("#".join(words)) show_words("story.txt")

A marked line continues the line above it. In your file, write it on the same line.

Input file

story.txt3 lines
Python is easy to learn.
Files store data permanently.
Practice every program.

Output

$ python words_separated_by_hash.py
Python#is#easy#to#learn. Files#store#data#permanently. Practice#every#program.

✓ Printed by running this program, not typed by hand.

Result

Each of the three lines of story.txt was displayed with its words joined by #, e.g. "Python#is#easy#to#learn.". The full stops stay attached to their words because split() splits only on spaces.

Viva voce: what the examiner may ask

01What does readlines() return?

A list in which each item is one line of the file, including its \n.

02Why is split() used without an argument?

It splits on any spaces and also removes the \n at the end of the line.

03What is the advantage of the with statement?

The file is closed automatically when the block ends.

Variations for the lab test

  1. Print a # after every word, including the last one.
  2. Display only the words that have more than 4 letters.
  3. Display the lines in reverse order.
! Common mistake Writing print(line.replace(" ", "#")) leaves the \n in each line and prints an extra blank line after every line.
Back to the 12-CS index