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

45 views Asked by At

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.

2

There are 2 answers

0
Timeless On BEST ANSWER

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)
0
refik On

I figured out myself, I also leave my solution here for those who have the same problem. Also thanks to @Timeless for his answer, it is a much more organized code than mine.

f1 = open("directory path\\f1.txt", "r") 
f2 = open("directory path\\f2.po", "r")

#transferring file lines to lists
listOfAllTxtLines = f1.readlines()
listOfAllPoLines = f2.readlines()

f1.close()
f2.close()

#Replacing lines which contains "msgstr" in f2.po with lines in f1.txt
j = 0
i = 0
for line in listOfAllPoLines:
    if "msgstr" in line:
        listOfAllPoLines[i] = listOfAllTxtLines[j]
        j += 1
    i += 1

#creating a new .po file
f3 = open("directory path\\f2_NEW.po", "w")
f3.close()

f4 = open("directory path\\f2_NEW.po", "a")

#writing new lines to the new .po file
for line in listOfAllPoLines:
    f4.write(line)

f4.close()