How to 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 head to write the data. Now  we initiate a for loop to integrate over or not and if thei

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)

input_file_name = 'input.txt'

output_file_name = 'output.txt'
copy_odd_lines(input_file_name, output_file_name)

 

r line is odd then copy the line from the file and write it in the output.

Output:

Hello

Python

Hello
Python

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top