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

PYTHON编程:搜索和替换文件中的文本,python,Python,我是PYTHON新手,正在尝试编写脚本来替换文本文件中的文本。这就是我在使用Python 3.1时想到的。但是我有一些错误。谁能帮帮我吗 #**************************************************************** # a Python code to find and replace text in a file. # search_replace.py : the python script #*********************

我是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...' )


关于

首先,我不确定这是否是您将代码联机时的错误,但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语句,包括一个字符串,如“字符串”

如果您输入一个文件路径,如
“E:\\search\u replace\\srtest.txt”
,oldFileName将是
“old-E:\\search\u replace\\srtest.txt”
,tempFileName将是
“temp-E:\\search\u replace\\srtest.txt”
,两者都无效

尝试这样做:

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

如果你更具体地说明你遇到的错误,而不是让人们阅读你所有的代码并运行它,那将是礼貌的。嘿,谢谢你的快速回复!缩进只是把代码放在这里的问题:)。和原始输入()??我在网上看到Python不再支持这个命令。这就是我不使用它的原因:(我已经成功地运行了您的脚本,修复了缩进,并将input()替换为raw_input()。请阅读我描述的差异,如果它对您有效,请接受答案。我使用raw_input()>>textToSearch=raw_input(“>”)得到以下错误NameError:name'raw_input'未定义Hey抱歉,忘记您使用的是Python 3.1,其中raw_input()已转换为input()。您有哪些错误?请编辑您的问题以包含它们。我正在使用input()运行您的脚本,没有错误在Python 3.1Hey中!感谢您的指导,如果我的提问方法有点不清楚,请原谅!我刚刚安装了2.6,并使用了raw_input()。它工作正常:),在将目标文件移动到驱动器的根目录后,我再次使用3.1执行它,并且工作正常!但是,当我尝试使用fileToSearch=open()使用类似E:\\PYcodes\\search\u replace\\srtest.txt的路径时,会收到一条消息“没有这样的文件或目录”