Remove all the lines that contain the character `a’ in a file and write it to another file.

Karthika A
Guvi
Published in
1 min readDec 16, 2019

For Basics on File operations please do read our previous blog:

With the above inputs, replacing ‘a’ in all the lines and printing it to another file our objective will be satisfied.

write()

write(string) : Inserts the string in a single line in the text file.

File_object.write(line)

So to remove all the lines that contain the character `a’ in a file and write it to another file we can revise the code as follows:

try:
filepath = ‘’#path of file to be read-sepeated by //
with open(filepath) as fp,open(‘’, ‘w’) as outfile:#new file path
for cnt, line in enumerate(fp):
line=line.replace(‘a’,’’)
outfile.write(line)
finally:
fp.close()

--

--