简体   繁体   中英

Replace string in line without adding new line?

I want to replace string in a line which contain patternB, something like this:

from:

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

to:

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

I have code like this:

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)

It do not replace the line contain "patternB" as expected, but add an new line below it like :

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

What can I do with my code?

You can use str.replace :

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

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

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

Of course it is, since you append line to dummy in the beginning of the for loop and then the modified version again in the "if" statement. Also why check for Pattern A if you treat is as you treat everything else?

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)

If you want to keep line by line iterator (for a big file)

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

This is slower than other responses, but enables big file processing.

This should work

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM