“Read a text file line by line and display each word separated by a #” is a popular file-handling practical in Class 12 computer science. The program opens a text file, reads one line at a time, splits each line into words and prints every word followed by a #. In this post you will see the program in Python, C and Java, a step-by-step dry run, ten other ways to write it, and answers to common questions. Use the interactive tool below to type your own file contents and watch every line and word being processed.
Type the contents of story.txt and watch the program read it line by line and put a # between the words.
Graphical view
Code
Output
What You Will Learn
- The problem statement
- How a text file is read line by line
- The program in Python, C and Java
- Dry run with an example file
- Other ways: join(), with open, replace(), writing to a file and more
- Common mistakes, practice questions and FAQ
Problem Statement
Read a text file line by line and display each word separated by a #.
Suppose a text file named story.txt contains these three lines:
Welcome to my website
Learn Python with fun
Practice every day
The program should print every word followed by a #, one line of output for each line of the file:
Welcome#to#my#website#
Learn#Python#with#fun#
Practice#every#day#
The interactive tool above lets you type up to five lines of file contents instead of creating a real file.
How a Text File Is Read Line by Line
A text file is a long string of characters with a special end-of-line character (\n) after each line. To read it you follow three steps:
- Open the file with
open("story.txt", "r"). The mode"r"means read. The function returns a file object, which we store in the variablef. - Read the lines. A
for line in f:loop gives you one line at a time, which uses little memory even for a large file. - Close the file with
f.close()to release it.
Inside the loop, each line is a string such as "Welcome to my website\n". The method split() with no arguments cuts a string at every group of spaces, tabs and newlines and returns a list of words. It also removes the end-of-line character and ignores extra spaces. Printing each word with end="#" puts a # after it instead of the usual new line, and the empty print() at the end of the line moves to the next line of output.
Before running the program, create story.txt in the same folder as the program (with Notepad, or with the short Python program in the practice section), because a relative file name is looked up in the current working folder.
The Program
Logic:
- Open
story.txtfor reading. - For every line in the file, split it into a list of words.
- Print each word followed by
#, staying on the same output line. - After the last word of the line, print a new line.
- Close the file.
Python program
f = open("story.txt", "r")
for line in f:
words = line.split()
for w in words:
print(w, end="#")
print()
f.close()
Output
Welcome#to#my#website#
Learn#Python#with#fun#
Practice#every#day#
C program
#include <stdio.h>
#include <string.h>
int main() {
FILE *f = fopen("story.txt", "r");
char line[200];
while (fgets(line, 200, f) != NULL) {
char *w = strtok(line, " \t\r\n");
while (w != NULL) {
printf("%s#", w);
w = strtok(NULL, " \t\r\n");
}
printf("\n");
}
fclose(f);
return 0;
}
Welcome#to#my#website#
Learn#Python#with#fun#
Practice#every#day#
C reads a line with fgets(), and strtok() cuts it into words at spaces, tabs and line ends. The first call gives the first word, and every call with NULL gives the next word, until it returns NULL. Note that strtok() changes the line it is cutting. If the file does not exist, fopen() returns NULL, so a real program should check that before reading (see the safe version in the FAQ).
Java program
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordsWithHash {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("story.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] words = line.trim().split("\\s+");
for (String w : words) {
if (w.length() > 0) {
System.out.print(w + "#");
}
}
System.out.println();
}
br.close();
}
}
Welcome#to#my#website#
Learn#Python#with#fun#
Practice#every#day#
Save this file as WordsWithHash.java. BufferedReader.readLine() returns the next line without the newline, and null at the end of the file. trim().split("\\s+") cuts at one or more spaces. For an empty line the array holds one empty string, so the w.length() > 0 test prevents printing a stray #. The throws IOException is required because file operations can fail.
Dry Run
For the first line of story.txt, Welcome to my website:
| Step | Statement | Value | Output so far |
|---|---|---|---|
| 1 | f = open(“story.txt”, “r”) | file is open | |
| 2 | for line in f | line = “Welcome to my website\n” | |
| 3 | words = line.split() | [“Welcome”, “to”, “my”, “website”] | |
| 4 | print(w, end=”#”) | w = “Welcome” | Welcome# |
| 5 | print(w, end=”#”) | w = “to” | Welcome#to# |
| 6 | print(w, end=”#”) | w = “my” | Welcome#to#my# |
| 7 | print(w, end=”#”) | w = “website” | Welcome#to#my#website# |
| 8 | print() | new line | Welcome#to#my#website#↵ |
The outer loop then repeats for the second and third lines, and finally f.close() closes the file. The program makes one trip round the outer loop per line, and one trip round the inner loop per word.
To see what readlines() gives you, and to see the hidden \n at the end of each line, print the lines with repr():
with open("story.txt", "r") as f:
lines = f.readlines()
print("Total lines:", len(lines))
for line in lines:
print(repr(line))
Total lines: 3
'Welcome to my website\n'
'Learn Python with fun\n'
'Practice every day\n'
Other Ways to Write the Program
Method 2: “#”.join() without a trailing #
The classic program leaves a # after the last word of every line. If you want the # only between the words, use "#".join(words), which glues the list items together with the given separator.
f = open("story.txt", "r")
for line in f:
words = line.split()
print("#".join(words))
f.close()
Welcome#to#my#website
Learn#Python#with#fun
Practice#every#day
Method 3: with open() closes the file for you
The with statement closes the file automatically, even if an error happens in the middle. This is the recommended style in modern Python.
with open("story.txt", "r") as f:
for line in f:
for w in line.split():
print(w, end="#")
print()
Method 4: replace() for single spaces
If the words are separated by exactly one space, line.strip().replace(" ", "#") does the job without a loop. strip() removes the end-of-line character first.
with open("story.txt", "r") as f:
for line in f:
print(line.strip().replace(" ", "#"))
But replace() is fragile. Here is a messy file with extra spaces and an empty line:
Hello world
three words here
The split() programs give clean results:
Hello#world#
three#words#here#Hello#world
three#words#here
whereas replace() turns every single space into a #:
Hello####world
three###words###here
So split() is the safer choice.
Method 5: Read the whole file at once
f.read() returns the entire file as one string. Splitting it gives the words of all lines together, but the line structure is lost, so everything ends up on one output line.
with open("story.txt", "r") as f:
words = f.read().split()
print("#".join(words))
Welcome#to#my#website#Learn#Python#with#fun#Practice#every#day
Method 6: Count the words of each line
with open("story.txt", "r") as f:
for line in f:
words = line.split()
print(len(words), "words:", "#".join(words))
4 words: Welcome#to#my#website
4 words: Learn#Python#with#fun
3 words: Practice#every#day
Method 7: Save the result in a new file
Instead of printing, you can write each result line to another file. The mode "w" creates the file, and if the file already exists, it erases its old content, so use a different name from the input file.
with open("story.txt", "r") as f, open("result.txt", "w") as out:
for line in f:
out.write("#".join(line.split()) + "\n")
print("Saved to result.txt")
Saved to result.txtThe file result.txt now contains:
Welcome#to#my#website
Learn#Python#with#fun
Practice#every#day
Method 8: Handle a missing file
If the file name or folder is wrong, open() raises FileNotFoundError. A try ... except block lets you show a friendly message instead of a long error.
try:
f = open("missing.txt", "r")
for line in f:
print("#".join(line.split()))
f.close()
except FileNotFoundError:
print("File not found. Check the file name and folder.")
File not found. Check the file name and folder.
C and Java: join version and error checking
C: # only between the words (a flag first remembers whether a word has been printed on the line):
#include <stdio.h>
#include <string.h>
int main() {
FILE *f = fopen("story.txt", "r");
char line[200];
while (fgets(line, 200, f) != NULL) {
int first = 1;
char *w = strtok(line, " \t\r\n");
while (w != NULL) {
if (first == 0) {
printf("#");
}
printf("%s", w);
first = 0;
w = strtok(NULL, " \t\r\n");
}
printf("\n");
}
fclose(f);
return 0;
}
C: check that the file opened
#include <stdio.h>
#include <string.h>
int main() {
FILE *f = fopen("story.txt", "r");
if (f == NULL) {
printf("File not found\n");
return 1;
}
char line[200];
while (fgets(line, 200, f) != NULL) {
char *w = strtok(line, " \t\r\n");
while (w != NULL) {
printf("%s#", w);
w = strtok(NULL, " \t\r\n");
}
printf("\n");
}
fclose(f);
return 0;
}
Java: String.join()
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordsJoin {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("story.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] words = line.trim().split("\\s+");
System.out.println(String.join("#", words));
}
br.close();
}
}
Save it as WordsJoin.java.
Java: Scanner with try-catch
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordsScanner {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new File("story.txt"));
while (sc.hasNextLine()) {
String line = sc.nextLine();
for (String w : line.split(" ")) {
if (w.length() > 0) {
System.out.print(w + "#");
}
}
System.out.println();
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}
Save it as WordsScanner.java.
Common Mistakes
- The file is not in the right folder. A relative name such as
"story.txt"is searched in the folder from which the program runs. If it is somewhere else, you get aFileNotFoundError(orNULLfromfopen()in C). Use the full path if needed. - Printing the line directly. Each line already ends with
\n, andprint()adds another one, so the output has blank lines between the lines:
f = open("story.txt", "r")
for line in f:
print(line)
f.close()
Welcome to my website
Learn Python with fun
Practice every day
- Forgetting split(). Without it you work with the whole line as one string. And
print(line.split())shows the Python list with brackets and quotes, not the words with #:
f = open("story.txt", "r")
for line in f:
print(line.split())
f.close()
['Welcome', 'to', 'my', 'website']
['Learn', 'Python', 'with', 'fun']
['Practice', 'every', 'day']
- Forgetting end=”#”. By default
print()ends with a new line, so every word goes on its own line. - Opening with “w” instead of “r”. Mode
"w"empties the file the moment it is opened. Always use"r"for reading. - Not closing the file. Always call
close(), or usewith open()so Python does it for you. - Splitting with split(” “) on messy text. With several spaces in a row,
split(" ")returns empty strings, which print as extra#signs. Usesplit()without arguments.
Practice Questions
- Create
story.txtfrom a Python program. Here is one way:
f = open("story.txt", "w")
f.write("Welcome to my website\n")
f.write("Learn Python with fun\n")
f.write("Practice every day\n")
f.close()
- Display the words separated by
*instead of#. - Count and display the total number of words in the file.
- Display only the words that start with a capital letter. Hint: w[0].isupper().
- Display the longest word in the file.
- Copy the file into another file, converting every word to upper case.
- Read the file and display the number of lines, words and characters.
Frequently Asked Questions
How do you read a text file line by line in Python?
Open it with open("story.txt", "r") and use for line in f:. The loop gives one line per turn, including the newline at the end. You can also use readline() for one line or readlines() for a list of all lines.
How do you display each word of a line separated by a #?
Split the line into words with line.split(), then print each word with print(w, end="#"). Or use print("#".join(words)) to put the # only between the words.
What does split() do?
Called without an argument, it cuts a string at every run of spaces, tabs and new lines and returns a list of the pieces. Leading, trailing and repeated spaces are ignored, so no empty words appear.
What is the difference between read(), readline() and readlines()?
read() returns the whole file as one string. readline() returns the next single line. readlines() returns a list with every line. A for loop over the file object reads line by line and is the best choice for big files.
Why are there blank lines in my output?
Every line read from a file ends with \n, and print() adds another new line. Use line.strip() or line.split() before printing, or print(line, end="").
Why do I get FileNotFoundError?
The file does not exist in the folder from which the program runs, or the name is spelled differently. Check the name and extension, put the file next to the program, or give the full path. A try ... except FileNotFoundError block can print a friendly message.
What is the difference between the modes “r”, “w” and “a”?
"r" reads an existing file. "w" writes and erases any old content. "a" appends new text at the end without erasing. For this program use "r".
Why use with open() instead of open() and close()?
with open(...) as f: closes the file automatically at the end of the block, even if an error occurs, so you cannot forget to close it.
How do I do this in C?
Open the file with fopen("story.txt", "r"), read each line with fgets(), and cut it into words with strtok(). Print each word with printf("%s#", w) and close the file with fclose(). Check that fopen() did not return NULL.
How do I do this in Java?
Use a BufferedReader with a FileReader. Call readLine() in a loop until it returns null, split each line with split("\\s+") and print the words with #. Declare throws IOException on main, or catch the exception.