In this python file program, we will get odd lines from files and append them to separate files. Let’s consider we have readcontent.txt file with the below content. We will get odd lines from files and append them to separate files with the help of the below-given steps.
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
Line9 : This is Australia.
Line10 : This is Zimbabwe.
Line11 : This is Nederland.
Line12 : This is scotland.
Line13 : This is Japan.
Steps to solve the program
- Open the first file by using open(“readcontent.txt“,”r”).
- Read the lines in the file using readlines().
- Now open the second file by using open(“writecontent.txt“,”w”).
- Where file name is the name of the file and w is writing mode.
- Use a for loop with the range function to iterate over the lines in the first file.
- If the line number is not divisible by 2 then add that line to the second file using write().
- Close the file.
# Open 1st file in read mode
f1 = open('readcontent.txt', 'r')
# Open 2nd file in write mode
f2 = open('writecontent.txt', 'w')
# Read lines of the file
lines_list = f1.readlines()
# Iterate over lines
for i in range(0, len(lines_list)):
# Check for odd line
if((i+1) % 2!= 0):
# Write lines to 2nd file
f2.write(lines_list[i])
else:
pass
# Close the file
f1.close()
f2.close()
Output: Now open the writecontent.txt file to see the odd lines from the readcontent.txt file.
Line1 : This is India.
Line3 : This is Canada.
Line5 : This is Africa.
Line7 : This is Germany.
Line9 : This is Australia.
Line11 : This is Nederland.
Line13 : This is Japan.