Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Copy Odd Lines of Text File to Another File using Python
In this article, we will show you how to copy only odd lines of a text file to another text file using Python. This is useful when you need to extract every alternate line starting from the second line.
Assume we have a text file named TextFile.txt with some sample content. We need to copy all the odd-numbered lines (2nd, 4th, 6th, etc.) to another file.
Sample Input File
TextFile.txt
Good Morning This is the Tutorials Point sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome everyone Learn with a joy
Algorithm
Following are the steps to copy odd lines from one file to another ?
Open the input text file in read mode using
open()functionOpen the output file in write mode
Use
readlines()to get all lines as a listLoop through the lines with their index positions
Check if the index is odd using modulus operator (
%)Write odd-indexed lines to the output file
Close both files
Example
The following program copies only odd lines of a text file to another file and prints the result ?
# Create sample input file
with open("TextFile.txt", "w") as f:
f.write("Good Morning\n")
f.write("This is the Tutorials Point sample File\n")
f.write("Consisting of Specific\n")
f.write("source codes in Python,Seaborn,Scala\n")
f.write("Summary and Explanation\n")
f.write("Welcome everyone\n")
f.write("Learn with a joy\n")
# Input text file
inputFile = "TextFile.txt"
# Opening the given file in read-only mode
readFile = open(inputFile, "r")
# Output text file path
outputFile = "PrintOddLines.txt"
# Opening the output file in write mode
writeFile = open(outputFile, "w")
# Read all lines from the input file
readFileLines = readFile.readlines()
# Traverse each line with its index
for lineIndex in range(len(readFileLines)):
# Check if the line number is odd (index 1, 3, 5, etc.)
# Modulus 2 gives 1 for odd numbers and 0 for even numbers
if lineIndex % 2 != 0:
# Write the odd line to output file
writeFile.write(readFileLines[lineIndex])
# Print the odd line (remove newline for clean output)
print(readFileLines[lineIndex].strip())
# Close both files
writeFile.close()
readFile.close()
print("\nOdd lines copied successfully to", outputFile)
This is the Tutorials Point sample File source codes in Python,Seaborn,Scala Welcome everyone Odd lines copied successfully to PrintOddLines.txt
Using enumerate() Method
A more Pythonic approach using enumerate() to get both index and line ?
# Create sample file
with open("sample.txt", "w") as f:
lines = ["Line 1\n", "Line 2\n", "Line 3\n", "Line 4\n", "Line 5\n"]
f.writelines(lines)
# Copy odd lines using enumerate
with open("sample.txt", "r") as input_file:
with open("odd_lines.txt", "w") as output_file:
for index, line in enumerate(input_file):
if index % 2 != 0: # Odd index (1, 3, 5...)
output_file.write(line)
print(f"Copied: {line.strip()}")
print("Process completed!")
Copied: Line 2 Copied: Line 4 Process completed!
Key Points
Index numbering: Python uses 0-based indexing, so odd indices (1, 3, 5) represent the 2nd, 4th, 6th lines
Modulus operator:
index % 2 != 0checks for odd numbersFile handling: Always close files or use context managers (
withstatement)Memory efficiency: For large files, consider reading line by line instead of
readlines()
Conclusion
We learned how to copy odd lines from one text file to another using Python file operations. The key is using the modulus operator to identify odd-indexed lines and proper file handling techniques.
