vendredi 12 juillet 2019

Finding and writing lines with a certain pattern from a text file to another

I'm using Python 3.7. I have two text files:

txt1:

NAME:APPLE
IMG:1.PNG
END

NAME:PEAR
IMG:1.GIF
END

txt2:

NAME:PEACH
IMG:2.PNG
END

I want to be able to generate a txt3:

NAME:PEACH
IMG:2.PNG
END

NAME:APPLE
IMG:1.PNG
END

My code and thinking:

imgTyp="PNG"

with open("txt1.txt",'r') as f1, open("txt2.txt",'r') as f2:
   f1line=set(f1.read().splitlines())
   f2line=set(f2.read().splitlines())

for line in f1line:
    if imgTyp in line:
        with open("txtTemp.txt","a") as fTemp:
            fTemp.writelines(**the lines with PNG in txt1 that is missing in txt2, and the line above and under each line**)
 **Then merge f2 and fTemp to get txt3.txt**    

I get stuck, and I'm not sure if I'm going with the correct logic. Can anyone help please?

Thanks in advance!

Poppel

Aucun commentaire:

Enregistrer un commentaire