I am new to PYTHON and trying to write script which replaces text in a text file. This is what I have come up with using Python 3.1. But I am having some errors. Would somebody help me, please?
#****************************************************************
# a Python code to find and replace text in a file.
# search_replace.py : the python script
#****************************************************************
import os
import sys
import fileinput
print ("Text to search for:")
textToSearch = input( "> " )
print ("Text to replace it with:")
textToReplace = input( "> " )
print ("File to perform Search-Replace on:")
fileToSearch = input( "> " ) # "rstest.txt"
#fileToSearch=open('E:\\search_replace\\srtest.txt','r')
oldFileName = 'old-' + fileToSearch
tempFileName = 'temp-' + fileToSearch
tempFile = open( tempFileName, 'w' )
for line in fileinput.input( fileToSearch ):
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
# Rename the original file by prefixing it with 'old-'
os.rename( fileToSearch, oldFileName )
# Rename the temporary file to what the original was named...
os.rename( tempFileName, fileToSearch )
input( '\n\n Press Enter to exit...' )
Regards
If you enter a file path such as
"E:\\search_replace\\srtest.txt", oldFileName will be"old-E:\\search_replace\\srtest.txt"and tempFileName will be"temp-E:\\search_replace\\srtest.txt", neither of which are valid.Try doing something like this instead: