Program to remove specific line in a file and write it to another file

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
  1. Open the first file in the reading mode using open(‘readcontent.txt’,’r’).
  2. Open the second file in the append mode using open(‘writecontent.txt’,’a’).
  3. Read the lines of the file using readlines().
  4. Use a for loop to iterate over the lines.
  5. Using an if statement to check whether ‘t’ is in the line or not.
  6. If yes then add that line to the second file using write().
  7. 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.

 

 

count the total number of consonants in a file.

display words from a file that has less than 5 characters.

Leave a Comment