Copy odd lines to another file

EasyFile Handling Programs · 7 of 38

Write a Python program to copy the odd-numbered lines of a file to a separate file.

Advertisement
Output
one
three
five

Approach

  1. Read with line numbers and write the odd ones to a second file.

Solution

Python
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())
Output
one
three
five

Line by line

Line 4

One with statement can open two files.

Advertisement

Learn the concept

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

More file handling programs

← All 38 File Handling Programs