“Remove all the lines that contain the character ‘a’ in a file and write them to another file” is a classic Class 12 computer science file-handling practical. The program reads a text file line by line, throws away every line that contains the letter a, and saves the remaining lines in a new file. In this post you will see the program in Python, C and Java, a line-by-line 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 each line being checked and copied.
Type the contents of story.txt and watch the program copy only the lines that have no letter a into new.txt.
Graphical view
Code
Contents of new.txt
What You Will Learn
- The problem statement
- The idea: read, check, write
- The program in Python, C and Java
- Dry run with an example file
- Other ways: ignore case, with open, list comprehension, user-chosen character and more
- Common mistakes, practice questions and FAQ
Problem Statement
Remove all the lines that contain the character ‘a’ in a file and write it to another file.
Suppose story.txt contains these six lines:
Welcome to my website
Learn with fun
Study hard
Apple juice is sweet
Python is easy
Enjoy coding
After the program runs, the new file new.txt must contain only the lines without the letter a:
Welcome to my website
Apple juice is sweet
Enjoy coding
The original file story.txt is not changed. The interactive tool above lets you type up to six lines instead of creating real files.
The Idea: Read, Check, Write
The word “remove” can be confusing, because the program does not delete anything from the original file. It copies only the lines you want to keep. A line is kept when it does not contain the character, so the result is a file without the unwanted lines. The program needs two files open at the same time:
- An input file opened in read mode
"r". - An output file opened in write mode
"w". Ifnew.txtdoes not exist, Python creates it. If it already exists, its old content is erased.
For every line of the input file there are two decisions: "a" not in line is checked, and if it is True, the line is written to the output file with fout.write(line). A line read from a file already ends with a new line character (\n), so writing it back keeps the line structure.
The test "a" in line asks whether the character appears anywhere in the line. It works for a character or a longer piece of text and it is case-sensitive, so a capital A does not count.
The Program
Logic:
- Open
story.txtfor reading andnew.txtfor writing. - Read the input file line by line.
- If the line does not contain “a”, write it to the output file.
- Close both files, so that everything is saved.
Python program
fin = open("story.txt", "r")
fout = open("new.txt", "w")
for line in fin:
if "a" not in line:
fout.write(line)
fin.close()
fout.close()
After the program runs, new.txt contains:
Welcome to my website
Apple juice is sweet
Enjoy coding
C program
#include <stdio.h>
#include <string.h>
int main() {
FILE *fin = fopen("story.txt", "r");
FILE *fout = fopen("new.txt", "w");
char line[200];
while (fgets(line, 200, fin) != NULL) {
if (strchr(line, 'a') == NULL) {
fputs(line, fout);
}
}
fclose(fin);
fclose(fout);
return 0;
}
The file new.txt will contain exactly the same lines as the one the Python program creates.
fgets() reads one line, including its new line character. strchr(line, 'a') searches the line for the character and returns NULL when it is not found. fputs() writes the line to the output file. The header string.h is needed for strchr().
Java program
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RemoveLines {
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new FileReader("story.txt"));
BufferedWriter fout = new BufferedWriter(new FileWriter("new.txt"));
String line;
while ((line = fin.readLine()) != null) {
if (!line.contains("a")) {
fout.write(line);
fout.newLine();
}
}
fin.close();
fout.close();
}
}
Save this file as RemoveLines.java. readLine() returns the line without its new line character, so we call newLine() after writing it. contains("a") is the Java way of asking “is the text in the line?”. Both files must be closed, because a BufferedWriter keeps the text in a buffer until it is closed.
Dry Run
The program checks each line of the example file:
| Line | Text | “a” in line | “a” not in line? (is it written?) |
|---|---|---|---|
| 1 | Welcome to my website | False | Yes, line copied |
| 2 | Learn with fun | True | No, line removed |
| 3 | Study hard | True | No, line removed |
| 4 | Apple juice is sweet | False | Yes, line copied |
| 5 | Python is easy | True | No, line removed |
| 6 | Enjoy coding | False | Yes, line copied |
Only the lines without a are copied, so new.txt has 3 lines and 3 lines have been removed. Look at line 4, Apple juice is sweet. It has a capital A but no lowercase a, so it is copied. That is correct for the question as it is written, because ‘a’ and ‘A’ are different characters.
Other Ways to Write the Program
Method 2: Ignore the case
If “Apple” should count as well, convert a copy of the line to lowercase before the check. The original line is written unchanged.
fin = open("story.txt", "r")
fout = open("new.txt", "w")
for line in fin:
if "a" not in line.lower():
fout.write(line)
fin.close()
fout.close()
Now new.txt contains:
Welcome to my website
Enjoy coding
Method 3: with open() closes the files for you
One with statement can open both files. They are closed automatically at the end of the block, even if an error happens.
with open("story.txt", "r") as fin, open("new.txt", "w") as fout:
for line in fin:
if "a" not in line:
fout.write(line)
Method 4: List comprehension and writelines()
Read all lines into a list, build a new list of the lines to keep, and write the whole list at once. This is short, but it keeps the whole file in memory.
with open("story.txt", "r") as fin:
lines = fin.readlines()
keep = [line for line in lines if "a" not in line]
with open("new.txt", "w") as fout:
fout.writelines(keep)
print(len(lines) - len(keep), "lines removed")
3 lines removed
Method 5: Count the copied and removed lines
Two counters report what happened. The program then reads new.txt back to show it.
removed = 0
copied = 0
with open("story.txt", "r") as fin, open("new.txt", "w") as fout:
for line in fin:
if "a" not in line:
fout.write(line)
copied = copied + 1
else:
removed = removed + 1
print("Lines copied:", copied)
print("Lines removed:", removed)
with open("new.txt", "r") as f:
print(f.read())
Lines copied: 3
Lines removed: 3
Welcome to my website
Apple juice is sweet
Enjoy coding
Method 6: Let the user choose the character
Replace the fixed “a” with a variable, so the same program removes any character or even a word.
ch = input("Enter the character to remove: ")
with open("story.txt", "r") as fin, open("new.txt", "w") as fout:
for line in fin:
if ch not in line:
fout.write(line)
For the input e, the new file contains:
Study hard
Enjoy coding
Method 7: Keep the result in the same file
To change the original file itself, read all its lines first, and only then open it again in write mode. Opening it with "w" before reading would erase it.
with open("story.txt", "r") as f:
lines = f.readlines()
with open("story.txt", "w") as f:
for line in lines:
if "a" not in line:
f.write(line)
Method 8: The opposite: keep only the lines with a
Remove the word not, and the program keeps the lines that contain a:
fin = open("story.txt", "r")
fout = open("new.txt", "w")
for line in fin:
if "a" in line:
fout.write(line)
fin.close()
fout.close()
Learn with fun
Study hard
Python is easy
Method 9: Handle a missing file
try:
fin = open("missing.txt", "r")
fout = open("new.txt", "w")
for line in fin:
if "a" not in line:
fout.write(line)
fin.close()
fout.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: ignore case, file check and Scanner
C: ignore the case by checking for both ‘a’ and ‘A’:
#include <stdio.h>
#include <string.h>
int main() {
FILE *fin = fopen("story.txt", "r");
FILE *fout = fopen("new.txt", "w");
char line[200];
while (fgets(line, 200, fin) != NULL) {
if (strchr(line, 'a') == NULL && strchr(line, 'A') == NULL) {
fputs(line, fout);
}
}
fclose(fin);
fclose(fout);
return 0;
}
C: check that the files opened, because fopen() returns NULL on failure:
#include <stdio.h>
#include <string.h>
int main() {
FILE *fin = fopen("story.txt", "r");
FILE *fout = fopen("new.txt", "w");
if (fin == NULL || fout == NULL) {
printf("File error\n");
return 1;
}
char line[200];
while (fgets(line, 200, fin) != NULL) {
if (strchr(line, 'a') == NULL) {
fputs(line, fout);
}
}
fclose(fin);
fclose(fout);
return 0;
}
Java: ignore the case (save as RemoveLinesIC.java): the only change is line.toLowerCase().contains("a").
Java: Scanner and PrintWriter (save as RemoveLinesScanner.java):
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class RemoveLinesScanner {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("story.txt"));
PrintWriter pw = new PrintWriter("new.txt");
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.indexOf('a') == -1) {
pw.println(line);
}
}
sc.close();
pw.close();
}
}
Common Mistakes
- Using strip() when writing.
strip()removes the new line at the end of the line, so the lines run together in the new file:
fin = open("story.txt", "r")
fout = open("new.txt", "w")
for line in fin:
if "a" not in line:
fout.write(line.strip())
fin.close()
fout.close()
Welcome to my websiteApple juice is sweetEnjoy coding
- Reversing the test. Writing
if "a" in linekeeps the lines that should be removed, which is Method 8. Read the problem statement carefully: remove the lines with a means keep the lines without a. - Opening the same file for reading and writing. Mode
"w"erases the file at the moment it is opened. This program ends with an empty story.txt and no output at all:
fin = open("story.txt", "r")
fout = open("story.txt", "w")
for line in fin:
if "a" not in line:
fout.write(line)
fin.close()
fout.close()
After this program runs, story.txt is empty, and the original text is lost. Always write to a different file, or read the lines into a list before you open the file for writing.
- Forgetting to close the output file. Written text waits in a buffer and may not reach the disk until the file is closed. Call
fout.close()or usewith open(). - Forgetting that ‘a’ and ‘A’ are different. A plain
"a" in linetest does not catch a capital A. Useline.lower()if both should count. - Opening the output with “r”. Read mode cannot write, and it fails if the file does not exist. Use
"w"for a new file or"a"to add to an existing one. - Wrong file location. A relative file name is searched in the folder from which the program runs. If it is somewhere else, you get a
FileNotFoundError(orNULLfromfopen()in C).
Practice Questions
- Remove the lines that contain the word “the” and write them to another file.
- Write the lines that contain ‘a’ to one file and the other lines to a second file.
- Remove the lines that start with a vowel. Hint: line[0] in “aeiouAEIOU”.
- Remove the empty lines of a file. Hint: line.strip() == “”.
- Remove the lines that are longer than 20 characters.
- Copy the file and put the line number before every kept line.
- Display the number of lines of the input file and of the output file.
Frequently Asked Questions
How do you remove lines containing a character from a file in Python?
Open the input file in read mode and a second file in write mode. Loop over the input lines, and write a line to the output file only when "a" not in line. The lines with the character are never written, so they are missing from the new file.
Does the program delete the lines from the original file?
No. It copies the wanted lines into a new file, and the original file stays unchanged. If you want to change the original, read its lines into a list first and write the kept lines back (Method 7).
What does the test “a” in line do?
It checks whether the text "a" appears anywhere inside the string line and returns True or False. It is case-sensitive.
How do I remove lines with both a and A?
Convert a copy of the line to lowercase before the test, as in if "a" not in line.lower():. The line itself is written unchanged.
What is the difference between the file modes “r”, “w” and “a”?
"r" reads an existing file, "w" creates a file or erases an existing one and writes, and "a" adds text at the end without erasing. For the output file of this program use "w".
Why must I close the files?
Closing a file saves any buffered text and frees the file for other programs. If you forget fout.close(), some of the written lines may be missing from the file. The with open() statement closes the files for you.
Why are all the lines joined in my new file?
Each line read from a file ends with a new line character. If you remove it with strip() or rstrip() before writing, the lines are written one after another. Write the line as it is, or add "\\n" yourself.
What happens if no line contains the character?
All lines are copied, and new.txt is an exact copy of the input file. If every line contains the character, new.txt is created but stays empty.
How do I do this in C?
Open both files with fopen(), read each line with fgets(), test it with strchr(line, 'a') == NULL, write the kept lines with fputs(), and close the files with fclose(). Check that fopen() did not return NULL.
How do I do this in Java?
Use a BufferedReader to read lines and a BufferedWriter to write them. Keep a line when !line.contains("a"), call newLine() after each write(), and close both files. Declare throws IOException on main.