Program to copy odd lines of text file to another file using Python

by | Jul 23, 2021 | Python Programs

Home » Python » Python Programs » Program to copy odd lines of text file to another file using Python

Introduction

The task is to copy the odd lines text to another file.

Program to copy odd lines of text file to another file using Python

Program

readFile = open("first.txt", "r") 
writeFile = open("updated.txt", "w") 


lines = readFile.readlines() 
type(lines) 
for idx in range(0, len(lines)): 
#check for odd lines
    if(idx % 2 != 0): 
        writeFile.write(lines[idx]) 
    else: 
        pass
writeFile.close() 
readFile.close() 
writeFile = open("updated.txt", "r") 


lines1 = writeFile.read() 


print(lines1) 
writeFile.close()

Output

Program to copy odd lines of text file to another file using Python Output

Explanation

Approach:

  • Open the text files in read mode and empty text file in write mode.
  • Read the lines of text file and assign to a variable.
  • Traverse through all the lines in range(0, len(lines)) and check whether the idx is divisible by 2.
  • If idx is not divisible by 2, write the content of line to another file else if it is divisible the skip and move to next idx.
  • Close the files.
  • Open the file and read its content. Print the content on screen.
  • Close the file.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author