Remove all lines that contain the character 'a' from a file and write them to another file
Expt. No.08
Page No.16
Move lines containing 'a'
Aim
To write a Python program that removes all lines containing the character 'a' from a file and writes them to another file.
Concepts used
Algorithm
- Read all lines of the source file into a list.
- Make two lists: lines that contain 'a' and lines that don't.
- Write the lines with 'a' to the second file with writelines().
- Write the remaining lines back to the source file (mode "w" overwrites it).
- Display how many lines were moved.
Program
# Move the lines containing 'a' to another file def remove_lines(source, target): with open(source, "r") as f: lines = f.readlines() keep = [] removed = [] for line in lines: if "a" in line: removed.append(line) else: keep.append(line) with open(target, "w") as f: f.writelines(removed) with open(source, "w") as f: f.writelines(keep) print(len(removed), "line(s) moved to", target) print(len(keep), "line(s) left in", source) remove_lines("source.txt", "with_a.txt")
A marked line continues the line above it. In your file, write it on the same line.
Input file
source.txt5 lines
Python is a programming language It is simple to use Files keep data We print output Lists hold items
Output
$ python remove_lines_with_a.py
2 line(s) moved to with_a.txt
3 line(s) left in source.txt
✓ Printed by running this program, not typed by hand.
Contents of source.txt
source.txtafter the run
It is simple to use We print output Lists hold items
Contents of with_a.txt
with_a.txtafter the run
Python is a programming language Files keep data
Result
Two lines contained 'a' and were moved to with_a.txt; the other three stayed in source.txt. The check is case-sensitive, so only the lowercase letter a was looked for.
Viva voce: what the examiner may ask
01What happens to a file's old contents when it is opened in mode "w"?
They are erased; the file starts empty.
02How is writelines() different from write()?
write() writes one string; writelines() writes every string in a list. Neither adds \n by itself.
03Why are all lines read before the file is rewritten?
Opening the same file in "w" mode first would erase it before it could be read.
Variations for the lab test
- Make the check case-insensitive so lines with 'A' also move.
- Copy only the lines that end with a full stop.
- Append the moved lines to the target file instead of overwriting it.
! Common mistake Opening the source in "w" mode before reading it wipes out all its lines.