python-3.xfilereplacefindandmodify

how to replace multiple duplicate strings in a file without deleting anything else python 3


Ok so I have this code:

for line in fileinput.FileInput("zero.html",inplace=1):
    if '{problem}' in line:
        rep = 'a dynamic var'
        line = line.replace('{problem}', rep)
        print(line)

Now, the problem is that it replaces the text fine, but it deletes all other lines without '{problem}' in it. How can I replace '{problem}' with something else, without deleting the other lines? Also, I have multiple occurrences of '{problem}' in my file, and I want each one to be changed to a different, random string. Thanks!


Solution

  • The if statement doesn't say what to do with the line if it doesn't contain '{problem}'. So as written, your code just ignores those lines. You could add an else clause that prints the line. Or you could just drop the if test, like this:

    for line in fileinput.FileInput("zero.html", inplace=1):
        rep = 'a dynamic var'
        line = line.replace('{problem}', rep)
        print(line)
    

    The replace method will leave the line unchanged if it doesn't contain '{problem}'.