twigg
twigg

Reputation: 3993

python string find and replace in text file

I'm reading a file and replacing a text string. I'm doing this for a few different strings, I know this isn't the most effeciant code I'm just trying to get it working. Here's what I have:

    for line in fileinput.input(new_config, inplace=1):
        print line.replace("http://domain.com", self.site_address)
        print line.replace("dbname", self.db_name)
        print line.replace("root", self.db_user)
        print line.replace("password", self.db_pass)
        print line.replace("smvc_", self.prefix

this works but it also writes every line in the file 5 times and only replaces the string on the first attempt on not on the new lines it creates (doesn't matter if it matches the string or not)

Upvotes: 1

Views: 1276

Answers (3)

jrwren
jrwren

Reputation: 17898

for line in fileinput.input(new_config, inplace=1):
    print line.replace(
        "http://domain.com", self.site_address).replace(
        "dbname", self.db_name).replace(
         "root", self.db_user).replace(
         "password", self.db_pass).replace("smvc_", self.prefix)

Done by copying and pasting what you wrote and using only the delete key and re-indenting. No characters added except the last closing paren.

Alternatively, this format may be clearer. It uses the backslash character to split the one line in a neater way, for better readability:

    print line.replace("http://domain.com", self.site_address) \
              .replace("dbname", self.db_name) \
              .replace("root", self.db_user) \
              .replace("password", self.db_pass) \
              .replace("smvc_", self.prefix)

Upvotes: 2

Tenzin
Tenzin

Reputation: 2505

You can read a file line by line.
And at every line look for the word you would like to replace.

For example:

line1 = 'Hello World There'
def Dummy():
    lineA = line1.replace('H', 'A')
    lineB = lineA.replace('e', 'o')
    print(lineB)

Dummy()

Then wirte lineB to a file.

Upvotes: -1

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

You just need to treat it as one string and apply all replacements to it.

for line in fileinput.input(new_config, inplace=1):
    line = line.replace("http://domain.com", self.site_address)
    line = line.replace("dbname", self.db_name)
    line = line.replace("root", self.db_user)
    line = line.replace("password", self.db_pass)
    line = line.replace("smvc_", self.prefix)
    print line

If it doesn't find any of those targets it will just not make any change to the line string so it will just replace what it DOES find.

Upvotes: 4

Related Questions