Python program to copy odd lines of one file to other (original) (raw)

Last Updated : 21 Jan, 2026

Given a text file, the task is to copy specific lines or odd lines from the input file to a new output file.

**Example: **Input.txt

Hello
World
Python
Language

**Output.txt

Hello
Python

Using enumerate()

enumerate() provides both the line number and the line content while iterating. This makes it easy to conditionally copy lines.

Python `

with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile: for ln, line in enumerate(infile, 1): if ln % 2 != 0: outfile.write(line)

`

**Output

Hello
Python

**Explanation:

**Note: Keep your file in the same directory.

For very large files, using iterators is memory-efficient. itertools.islice() allows skipping lines without loading the entire file into memory.

Python `

from itertools import islice

with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile: for line in islice(infile, 0, None, 2): # Start=0, Step=2 outfile.write(line)

`

**Output

Hello
Python

**Explanation: for line in islice(infile, 0, None, 2): efficiently selects every second line starting from the first line (line index 0) without loading the entire file into memory.

Using a Counter Variable

Use a counter to track line numbers and copy odd-numbered lines to another file.

Python `

with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile: count = 1 for line in infile: if count % 2 != 0: outfile.write(line) count += 1

`

**Output

Hello
Python

**Explanation:

Using readlines() with Slicing

This method reads all lines into a list and uses Python slicing to select lines.

Python `

with open('input.txt', 'r') as infile: lines = infile.readlines()

with open('output.txt', 'w') as outfile: for line in lines[0::2]: outfile.write(line)

`

**Output

Hello
Python

**Explanation:

Using filter() and lambda

filter() with lambda can pick lines that meet a condition, like odd-numbered lines, without counting them manually.

Python `

with open('input.txt', 'r') as infile: lines = list(infile)

with open('output.txt', 'w') as outfile: for _, line in filter(lambda x: x[0] % 2 == 0, enumerate(lines)): outfile.write(line)

`