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
Words separated by #: Python#is#easy#to#learn# Files#keep#data#after#the#program#ends# Practice#makes#a#programmer#perfect#
How it works
- The program first writes three lines to
story.txt, so it has a file to read. - Opening the file with
with open("story.txt", "r") as fcloses it automatically when the block ends. for line in freads the file one line at a time.line.split()breaks the line into words wherever there are spaces, and it also drops the newline at the end of the line.print(word, end="#")prints each word followed by # instead of a new line, and the emptyprint()ends the output line once all its words are printed.
Another way to write it
Using join (no # after the last word)
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.
Related programs
- Count Words in a Text File
- Count the Words "Me" and "My" in a Text File
- Display Lines Starting with T in a Text File
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Read a File Line by Line
All Python programs · CBSE class 12 practical file · Python exercises