[Python] How can I compare the contents of two text files in Python?

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    I need to write a script that compares the contents of two text files. I want to give an example for what I want:

    file1.txt's content:

    New York
    Los Angeles
    Miami


    file2.txt's content:

    New York
    Orlando
    Miami
    Dc


    I want to compare the two texts and print the different added or missed elements.

    My code attempt is here:

    from difflib import Differ

    from numpy import diff

    myfile1 = input("Enter First File's name for compare : ")
    myfile2 = input("Enter Second File's name for compare : ")

    ch1 = myfile1.split(".")
    ch2 = myfile2.split(".")

    if ch1[1] == "txt" and ch2[1] == "txt":
    with open(myfile1) as file_1, open(myfile2) as file_2:
    differ = Differ()

    for line in differ.compare(file_1.readlines(), file_2.readlines()):
    print(line)

    else:
    print("File format Eror !")


    I already use difflib, but if some content is missed this thing is adding "-" in front of the name, also if content is added "+" is added in front of the name. I need to print added and missed contents.

    Continue reading...

Compartilhe esta Página