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.
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:
- 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.
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.
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:
- 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.
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:
- 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.
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)
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.