Home > Mobile >  Python: replace string in each line
Python: replace string in each line

Time:12-24

I'm trying to replace each "zzz" with a number. There is no output at execution and the file content remains the same. Here's what I have:

n = 0
file = open("filename", "a")
for line in file:
    if "zzz" in line:
        line.replace("zzz", n, 1)
        n  = 1

CodePudding user response:

There are a few issues here. First, the replace method doesn't alter the string in place but rather creates a new string. Therefore, if you don't assign the new value to something, you're going to lose it.

Second, you're trying to read from the file but you're opening it in append mode. You need to open it with "r" instead of "a".

Third, you can't pass an integer (n) as the second argument to replace. You need to convert it to a string.

Finally, you're not writing the contents back to the file. That's why it's unchanged. I recommend reading all of the data in, altering it, and then re-opening the file in write mode.

n = 0

with open("filename", "r") as f:
    lines = f.readlines()

for k, line in enumerate(lines):
    if "zzz" in line:
        lines[k] = line.replace("zzz", str(n), 1)
        n  = 1

with open("filename", "w") as f:
    f.write("".join(lines))

CodePudding user response:

You need to assign the replace statement back to line variable.

n = 0
file = open("filename", "a")
for line in file:
    if "zzz" in line:
        line = line.replace("zzz", n, 1)
        n  = 1
  • Related