pythonfilefile-writing

Replacing Specific Lines in a File with Lines in a Different File in Python


I have a f1.txt and f2.po file and I want to replace certain lines (that contains the string "msgstr") in this f2.po file with lines in the f1.txt file.

I mean, the first line that contains the string "msgstr" should replace with the first line in the .txt file and the second line that contains the string "msgstr" should replace with the second line in the .txt file. I hope I've been able to explain it completely.

I know how to overwrite a file but I can't figure out how to overwrite only certain lines. I'de be very appreciated if you could help.


Solution

  • You can walk through the file f2.po and whenever a line contains "msgstr", call readline to ask for the corresponding line in f1.txt and if not, keep the original one.

    import fileinput
    
    with (
        open("f1.txt", "r") as f1,
        fileinput.input(files=("f2.po"), inplace=True) as f2
    ):
        for line in f2:
            if "msgstr" in line:
                print(f1.readline(), end="")
            else:
                print(line, end="")
    

    Alternatively, if you don't want to modify f2.po inplace, add a third open :

    with (
        open("f1.txt", "r") as f1,
        open("f2.po", "r") as f2,
        open("f3.po", "w") as f3
    ):
        for line in f2:
            if "msgstr" in line:
                f3.write(f1.readline())
            else:
                f3.write(line)