Python program to copy odd lines of one file to other

Created with Sketch.

 

Python program to copy odd lines of one file to other

Write a python program to read the contents of a file and copy only the content of odd lines into a new file.

Examples:

Input : Hello
        World
        Python
        Language
Output : Hello
         Python

Input : Python
        Language
        Is
        Easy
Output : Python
         Is

Approach to the problem

1) Open file name bcd.txt in read mode and assign it to fn.
2) Open file name nfile.txt in write mode and assign it to fn1.
3) Read the content line by line of the file fn and assign it to cont.
4) Access each element from 0 to the length of cont.
5) Check if i is not divisible by 2 then write the content in fn1 else pass.
6) Close the file fn1.
7) Now open nfile.txt in read mode and assign it to fn1.
8) Read the content of the file and assign it to cont1.
9) Print the content of the file and then close the file fn and fn1 .

 

# open file in read mode
fn = open('bcd.txt', 'r')
 
# open other file in write mode
fn1 = open('nfile.txt', 'w')
 
# read the content of the file line by line
cont = fn.readlines()
type(cont)
for i in range(0, len(cont)):
    if(i % 2 ! = 0):
        fn1.write(cont[i])
    else:
        pass
 
# close the file
fn1.close()
 
# open file in read mode
fn1 = open('nfile.txt', 'r')
 
# read the content of the file
cont1 = fn1.read()
 
# print the content of the file
print(cont1)
 
# close all files
fn.close()
fn1.close()
Output : Python
         Is
 

Python program that copies the odd lines of one file to another file:

# Open the input and output files
with open('input_file.txt', 'r') as input_file, open('output_file.txt', 'w') as output_file:
    # Loop through each line in the input file
    for i, line in enumerate(input_file):
        # Check if the line number is odd
        if i % 2 == 0:
            # If it is, write the line to the output file
            output_file.write(line)

Explanation:

  • We use the with statement to open both the input and output files. This ensures that the files are properly closed after they are used.
  • We use a for loop to loop through each line in the input file. The enumerate function is used to get both the line number and the line itself.
  • We check if the line number is odd by using the modulo operator %. If the line number is even, the result will be 0 and the line will be skipped. If the line number is odd, the result will be 1 and the line will be copied to the output file.
  • If the line number is odd, we write the line to the output file using the write method of the output file object.

Note that this program assumes that the input file exists and is readable and that the output file can be created or overwritten.

Leave a Reply

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