How do I search and replace text in a file using Python 3?
Here is my code:
JavaScript
x
27
27
1
import os
2
import sys
3
import fileinput
4
5
print ("Text to search for:")
6
textToSearch = input( "> " )
7
8
print ("Text to replace it with:")
9
textToReplace = input( "> " )
10
11
print ("File to perform Search-Replace on:")
12
fileToSearch = input( "> " )
13
#fileToSearch = 'D:dummy1.txt'
14
15
tempFile = open( fileToSearch, 'r+' )
16
17
for line in fileinput.input( fileToSearch ):
18
if textToSearch in line :
19
print('Match Found')
20
else:
21
print('Match Not Found!!')
22
tempFile.write( line.replace( textToSearch, textToReplace ) )
23
tempFile.close()
24
25
26
input( 'nn Press Enter to exit...' )
27
Input file:
JavaScript
1
4
1
hi this is abcd hi this is abcd
2
This is dummy text file.
3
This is how search and replace works abcd
4
When I search and replace ‘ram’ by ‘abcd’ in above input file, it works as a charm. But when I do it vice-versa i.e. replacing ‘abcd’ by ‘ram’, some junk characters are left at the end.
Replacing ‘abcd’ by ‘ram’
JavaScript
1
4
1
hi this is ram hi this is ram
2
This is dummy text file.
3
This is how search and replace works rambcd
4
Advertisement
Answer
fileinput
already supports inplace editing. It redirects stdout
to the file in this case:
JavaScript
1
7
1
#!/usr/bin/env python3
2
import fileinput
3
4
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
5
for line in file:
6
print(line.replace(text_to_search, replacement_text), end='')
7