Open In App

Python program to copy odd lines of one file to other

Last Updated : 06 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Program to read the contents of a file and copy only the content of odd lines into a new file. By identifying whether the line number is odd or even in Python.

Examples:

Input :
            Hello
            World
            Python
            Language

Output : Hello
                Python

Explanation: The output file has only the odd line form the input file

Copy odd lines of one file to another file in Python

Here we first open the file in read mode from which we have to read the data and open the second file in write mode in which we have to write the data. Now we initiate a for loop to integrate over the input file and check whether the line is odd or not and if the line is odd then copy the line from the file and write it in the output file.

Python3




def copy_odd_lines(input_file, output_file):
    with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
        for line_number, line in enumerate(infile, 1):
            if line_number % 2 != 0:
                outfile.write(line)
 
# Example usage:
input_file_name = 'input.txt'
output_file_name = 'output.txt'
copy_odd_lines(input_file_name, output_file_name)


Output:

Hello 
Python

Note: Keep your input file in the same directory.

Python to write specific lines from one file to another file

Here we first open the file in read mode from which we have to read the data and open the second file in write mode in which we have to write the data. Now in input with the input file and output file, we also take a number of the specific lines which we need to copy from the input_file.

Python3




def copy_specific_lines(input_file, output_file, line_numbers):
    with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
        for line_number, line in enumerate(infile, 1):
            if line_number in line_numbers:
                outfile.write(line)
 
 
# Example usage:
input_file_name = 'input.txt'
output_file_name = 'output.txt'
# Put the line numbers you want to copy here
lines_to_copy = [1, 2]
copy_specific_lines(input_file_name,
                    output_file_name, lines_to_copy)


Output:

Hello 
Python

Note: Keep your file in the same directory.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads