![]() |
VOOZH | about |
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
enumerate() provides both the line number and the line content while iterating. This makes it easy to conditionally copy lines.
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.
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.
Use a counter to track line numbers and copy odd-numbered lines to another file.
Output
Hello
Python
Explanation:
This method reads all lines into a list and uses Python slicing to select lines.
Output
Hello
Python
Explanation:
filter() with lambda can pick lines that meet a condition, like odd-numbered lines, without counting them manually.
Output
Hello
Python
Explanation: