Table of Contents
Introduction
The task is to copy the odd lines text to another file.
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
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.
0 Comments