In this python file program, we will remove specific line in a file and write it to another file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.
#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.
Steps to solve the program
- Open the first file in the reading mode using open(‘readcontent.txt’,’r’).
- Open the second file in the append mode using open(‘writecontent.txt’,’a’).
- Read the lines of the file using readlines().
- Use a for loop to iterate over the lines.
- Using an if statement to check whether ‘t’ is in the line or not.
- If yes then add that line to the second file using write().
- Now close both files.
# open file read mode
f1=open('readcontent.txt','r')
# open file in append mode
f2=open('writecontent.txt','a')
# Read lines from the file
lines=f1.readlines()
# Iterate over lines
for line in lines:
# Check for t in the lines
if 't' in line:
# Write lines to writecontent.txt file
f2.write(line)
# Close the file
f1.close()
f2.close()
Output : Open writecontent.txt file to see the output.
I’m learning python at sqatools.
I’m from Australia.