Copy odd lines to another file
Write a Python program to copy the odd-numbered lines of a file to a separate file.
one three five
Approach
- Read with line numbers and write the odd ones to a second file.
Solution
with open("source.txt", "w") as f: f.write("one\ntwo\nthree\nfour\nfive\n") with open("source.txt") as src, open("odd.txt", "w") as dst: for i, line in enumerate(src, start=1): if i % 2 == 1: dst.write(line) print(open("odd.txt").read())one three five
Line by line
One with statement can open two files.
Learn the concept
New to this topic? Read the lesson, then come back.

