在不添加新行的情况下替换字符串?

时间:2016-06-27 08:31:13

标签: python python-2.7

我想替换包含patternB的行中的字符串,如下所示:

从:

some lines
line contain patternA
some lines
line contain patternB
more lines

为:

some lines
line contain patternA
some lines
line contain patternB xx oo
more lines

我有这样的代码:

inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []

for line in inputfile:
    dummy += line
    if line.find("patternA") != -1:
        for line in inputfile:
            dummy += line
            if line.find("patternB") != -1:
                item = line.split()
                dummy += item[0] + " xx " + item[-1] + "\n"
                break
outputfile.write(dummy)

它不会替换包含" patternB"正如所料,但在它下面添加一个新行,如:

some lines
line contain patternA
some lines
line contain patternB
line contain patternB xx oo
more lines

我的代码怎么处理?

5 个答案:

答案 0 :(得分:0)

您可以使用str.replace

s = '''some lines
line contain patternA
some lines
line contain patternB
more lines'''

print(s.replace('patternB', 'patternB xx oo'))

答案 1 :(得分:0)

最简单的将是: 1.将所有文件读入字符串 2.调用string.replace 3.将字符串转储到文件

答案 2 :(得分:0)

当然是,因为你在for循环的开头附加了行,然后在“if”语句中再次添加修改后的版本。另外,为什么检查模式A,如果你对待的是你对待其他一切?

inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []

for line in inputfile:
    if line.find("patternB") != -1:
        item = line.split()
        dummy += item[0] + " xx " + item[-1] + "\n"
    else:
        dummy += line
outputfile.write(dummy)

答案 3 :(得分:0)

如果你想逐行保持迭代器 (对于一个大文件)

for line in inputfile:
    if line.find("patternB") != -1:
        dummy = line.replace('patternB', 'patternB xx oo')
        outputfile.write(dummy)
    else:
        outputfile.write(line)

这比其他响应慢,但可以进行大文件处理。

答案 4 :(得分:0)

这应该有用

import os

def replace():

    f1 = open("d:\myfile.abc","r")
    f2 = open("d:\myfile_renew.abc","w")
    ow = raw_input("Enter word you wish to replace:")
    nw = raw_input("Enter new word:")
    for line in f1:
        templ = line.split()
        for i in templ:
            if i==ow:
                f2.write(nw)
            else:
                f2.write(i)
        f2.write('\n')
    f1.close()
    f2.close()
    os.remove("d:\myfile.abc")
    os.rename("d:\myfile_renew.abc","d:\myfile.abc")

replace()