Drop lines containing 't'

EasyFile Handling Programs · 36 of 38

Write a Python program to copy a file to another file, skipping lines that contain the letter “t”.

Advertisement
Output
apple
cherry
melon

Approach

  1. Write only lines where "t" not in line.lower().

Solution

Python
with open("source.txt", "w") as f:    f.write("apple\nbutter\ncherry\nmelon\ntea\n") with open("source.txt") as src, open("filtered.txt", "w") as dst:    for line in src:        if "t" not in line.lower():            dst.write(line)print(open("filtered.txt").read())
Output
apple
cherry
melon

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Leave a Comment