PYTHON programming: Search and Replace text in a file [closed]
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:
oldFileName = "{}\\old-{}".format(*os.path.split(fileToSearch))
tempFileName = "{}\\temp-{}".format(*os.path.split(fileToSearch))
First off, I am not sure if this is an error in your putting your code online, but the body of your for loop is not indented.
for line in fileinput.input( fileToSearch ):
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
Should be
for line in fileinput.input( fileToSearch ):
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
Second, you are using the input() method where you most likely want raw_input(), which accepts string input such as characters to search. input() takes any python statement, including a string such as 'a string'
精彩评论