VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-copy-odd-lines-of-one-file-to-other/

⇱ Python program to copy odd lines of one file to other - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python program to copy odd lines of one file to other

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.

Output

Hello
Python

Explanation:

  • enumerate(infile, 1): gives line numbers starting from 1.
  • ln % 2 != 0: ensures only odd-numbered lines are written.

Note: Keep your file in the same directory.

Using itertools.islice()

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

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.

Output

Hello
Python

Explanation:

  • count = 1: initializes a counter.
  • if count % 2 != 0: checks for odd-numbered lines.
  • count += 1: increments the counter for the next line.

Using readlines() with Slicing

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

Output

Hello
Python

Explanation:

  • lines = infile.readlines(): Read all lines into a list.
  • for line in lines[0::2]: Select every second line starting from index 0 (odd-numbered lines).

Using filter() and lambda

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

Output

Hello
Python

Explanation:

  • enumerate(lines): generates (index, line) for every line.
  • lambda x: x[0] % 2 == 0: checks the actual line index, so duplicates are handled correctly.

Related Articles:

Comment
Article Tags:
Article Tags: