Comparing two text files in python

前端 未结 4 1391
执念已碎
执念已碎 2021-02-05 12:20

I need to compare two files and redirect the different lines to third file. I know using diff command i can get the difference . But, is there any way of doing it in python ? An

4条回答
  •  眼角桃花
    2021-02-05 12:53

    #compare 2 text files.
    
    test1filehandle = open("test1.txt", "r") #creating a file handle
    test2filehandle=open("test2.txt","r") #creating a file handle to read
    test3filehandle=open("test3.txt","w") #creating a file handle to write
    test1list= test1filehandle.readlines() #read the lines and store in the list
    test2list=test2filehandle.readlines()
    k=1
    for i,j in zip(test1list,test2list): #zip is used to iterate the variablea in 2 lists simultaneoously   
        if i !=j:
            test3filehandle.write("Line Number:" +str(k)+' ')
            test3filehandle.write(i.rstrip("\n") + ' '+ j)
        k=int(k)
        k=k+1;
    

提交回复
热议问题