Home > Back-end >  I can't understand what's wrong - Python multiple text replace dictionary
I can't understand what's wrong - Python multiple text replace dictionary

Time:12-05

I can't understand what happen. I'm trying to make this script to replace multiple text files using a list of pairs, but only the first pair is working, the others are not processed. Did I make any mistakes in the loops?

replacements = [
    ('Dog', 'Cat'),
    ('Lazy', 'Smart'),
    ('Fat', 'Slim'),
]

import re
import sys


if __name__ == "__main__":
    if len(sys.argv) < 2 or len(sys.argv) > 4:
        print("Invalid argument(s)")
        exit()
    with open(sys.argv[1], "r") as f:
        print(f"Reading {sys.argv[1]}")
        new_lines = ""

        for old, new in replacements:
            for l in f:
                new_lines  = re.sub(old, new, l)       
        
            
    with open(sys.argv[2] or sys.argv[1], "w") as f:
        print(f"Writing into '{sys.argv[2] or sys.argv[1]}'")
        f.write(new_lines)  
        

CodePudding user response:

The double for loop is causing the issue. Reading the file contents only once fixes the issue.

replacements = [
    ('Dog', 'Cat'),
    ('Lazy', 'Smart'),
    ('Fat', 'Slim'),
]

import re
import sys


if __name__ == "__main__":
    if len(sys.argv) < 2 or len(sys.argv) > 4:
        print("Invalid argument(s)")
        exit()
    with open(sys.argv[1], "r") as f:
        print(f"Reading {sys.argv[1]}")
        new_lines = f.read()

        for old, new in replacements:
            new_lines = re.sub(old, new, new_lines)
        
            
    with open(sys.argv[2] or sys.argv[1], "w") as f:
        print(f"Writing into '{sys.argv[2] or sys.argv[1]}'")
        f.write(new_lines)

The file will be read only once for the first replacement pairs, then it will be exhausted as all elements of the file have already been read once.
Therefore, for the next replacements, pairs file contents will not be read. That's why it's only working for Dog and Cat pair and not the rest.

  • Related