0

I have two files: file1.txt and file2.txt. I would like to only display the lines in result2.txt that are new / different from those in result1.txt.

I do this in bash using the following command:

diff file1.txt file2.txt | grep -E "^>" | sed 's/^..//'

Is this achievable using Python (without calling an OS command)?

2 Answers 2

1

See difflib a Python library for exactly this

Sign up to request clarification or add additional context in comments.

Comments

0

Go through the program and it is one of the lucid code, which takes advantage of a user defined function to look for changes between two files. ~~ do leave the comment if there is any queries.

def copy(name1 = input("Enter The Initial File Name : "), name2 = input("Enter The Change File Name : "), name3 = input("Enter The Nanme of The Output File : ")):
#initialisation from user if no parameter is provided    
    import os #to remove redundant output file, can be not used also    
    while True:

        try:
            f = open(name1,"r+") #'r+' because to read and write
            s = open(name2,"r+")
            o = open(name3,"w")

        except IOError:

            print("File not found !!!!")
            break

        while True:

            char1 = f.read(1)
            char2 = s.read(1)
            if (char1 == "" and char2 == ""): 
                break #if reached end of file
            if(char2 == ""):
                o.write(char1) #writing for difference in blank space
            elif(char1 == ""):
                o.write(char2) #writing for difference in blank space
            elif(char2 is not char1):
                o.write(char2) #compare and write

        f.close()
        s.close()
        o.close()
        print("The Changes Copied to",name3)
        break

copy()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.