PYTHON编程:搜索和替换文件中的文本

时间:2011-07-05 23:41:01

标签: python

我是PYTHON的新手,并尝试编写替换文本文件中的文本的脚本。这就是我用Python 3.1提出的。但我有一些错误。请问有人帮助我吗?

#****************************************************************
# 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...' )

此致

2 个答案:

答案 0 :(得分:1)

首先,我不确定你的代码是否在网上是错误的,但你的for循环的主体没有缩进。

for line in fileinput.input( fileToSearch ):
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()

应该是

for line in fileinput.input( fileToSearch ):
  tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()

其次,您正在使用input()方法,您最有可能需要raw_input(),它接受字符串输入(如要搜索的字符)。 input()接受任何python语句,包括诸如'a string'

之类的字符串

答案 1 :(得分:1)

如果您输入文件路径,例如"E:\\search_replace\\srtest.txt",则oldFileName将为"old-E:\\search_replace\\srtest.txt",tempFileName将为"temp-E:\\search_replace\\srtest.txt",两者均无效。

尝试做这样的事情:

oldFileName  = "{}\\old-{}".format(*os.path.split(fileToSearch))
tempFileName = "{}\\temp-{}".format(*os.path.split(fileToSearch))