【发布时间】:2014-01-13 12:26:30
【问题描述】:
我正在编写一个简单的 python 脚本,它解析一个文本文件并正在寻找一个字符串,如果找到该字符串,则将用另一个字符串替换该字符串,如果未找到该搜索字符串,则附加一个字符串。
我想要一些类似的东西:
#!/usr/bin/python2
import fileinput, glob, string, sys, os
from os.path import join
myfile="textfile.txt"
search_string="pussy"
replace_string1="tutti"
replace_string2="frutti"
replace_strings = replace_string1 + '\n' + replace_string2
stext = str(search_string);
rtext = str(replace_strings);
print "finding:\n" + stext + "\n\nreplacing with:\n" + rtext + "\n\nin:\n" + myfile
for line in fileinput.input(myfile,inplace=1):
lineno = 0
lineno = string.find(line, stext)
if lineno >=0:
line = line.replace(stext, rtext)
sys.stdout.write(line)
else:
print "append line"
所以如果我使用这个脚本将运行 if 语句和 else!怎么了?
【问题讨论】:
-
发布Python问题时需要使用正确的缩进;您的
if lineno >= 0测试甚至不是fileinput.input()循环的一部分,它前面的行使用 3 个空格而不是 4 个,但后面的行 do 使用 4。所有这些都使您的代码无效。跨度> -
你想用
lineno变量做什么?lineno总是会是0,所以lineno >= 0总是正确的。 -
是否要将文本附加到文件末尾,并且仅在未找到搜索文本时才添加?应该替换所有个搜索文本,还是只替换第一个?
标签: python string search file-io replace