开发者

PYTHON programming: Search and Replace text in a file [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

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'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜