Write a python program to remove all the lines that contain characters ‘a’ in a file and write it to another file

In this post, we will create a python program which will remove all the lines that contain character ‘a ‘ in file and write it to another file.

Program Logic:

  • Open input file say ‘assignment.txt’ in read mode and store in temporary file object say ‘input_file’
  • Open output file say ‘dataoutput.txt’ in write mode and store in temporary file object say ‘output_file’
  • Read the contents of input file using readlines()
  • Iterate through input file using for loop
  • Within for loop, if statement is used to check input file contains the character ‘a’ or not
  • Write only those lines that does not contain character ‘a’ in output file using write()
  • Close all input and output file

Below is implementation code/source code

Program to remove all lines that contain character ‘a’

The following text file is input file

The following file is output file which contain the output of above program after execution

We can also modify the program by writing lines that contain character ‘a’ in other file. Lets see how to write such type of programs.

Python program to remove all the lines that contain the character ‘a’ in a file and write it into other file.Write rest of lines that contain character ‘a’ in third file

Program to remove all lines that contain ‘a’ and write it in another file

The following is output file 1 that does not contain character ‘a’

dataoutput1.txt file

The following is output file 2 that contain character ‘ a’ in lines

Other python programs with complete solutions

<

Leave a Reply

Your email address will not be published.