user2653062
user2653062

Reputation: 717

How do I copy only the diff of the content from one file to another file?

I have two files, source file and dest file. I want to copy the content from this source file to the dest file, but not the whole content. Only that part which is there in the source file and not in dest file.

I tried to search and came across shutil module but I couldn't find any function that copies only the diff of content from one file to other.

How to do this in Python? Do we have any library function to accomplish this?

Example:

source.txt:     dest.txt
a               a
b               c
c               e
d               f
e

After the desired operation, it should be:

source.txt:     dest.txt
a               a
b               c
c               e
d               f
e               b
                d

Note that the order of lines doesn't matter.

Upvotes: 1

Views: 496

Answers (2)

MeetTitan
MeetTitan

Reputation: 3568

If you can arrange your files to be lists of lines, we can accomplish this very easily.

if len(lineList1) > len(lineList2):
    src = lineList1
    dst = lineList2
else
    src = lineList2
    dst = lineList1
for x in range(len(src)):
    if src[x] != dst[x]
        dst[x] = scr[x]

This snippet, finds the longest list, iterates over both, and if the line isn't the same on the destination, it is copied. Although I'm unsure the benefits of this approach over copying the file; except for practice.

EDIT

I think I understand. Try this snippet:

output = dst + [x for x in src if x not in dst]

This iterates over every line and if its not in dst it's added at the end.

Upvotes: 1

Tarun Venugopal Nair
Tarun Venugopal Nair

Reputation: 1359

Use difflib

import difflib
file1 = "PATH OF FILE 1"
file1 = open(file1, "r")
file2 = "PATH OF FILE 2"
file2 = open(file2, "r")
diff = difflib.ndiff(file1.readlines(), file2.readlines())
file1.close()
file2.close()
delta = ''.join(x[2:] for x in diff if x.startswith('- '))
fh = open("PATH OF FILE 2", "a")
fh.write(delta)
fh.close
fh = open("PATH OF FILE 2","r")
print fh.read()
fh.close()

Upvotes: 0

Related Questions