You can use difflib.Differ to return a single sequence of lines with a marker at the start of each line which describes the line. The markers tell you the following information about the line:

Marker Description
'- ' line unique to file 1
'+ ' line unique to file 2
' ' line common to both files
'? ' line not present in either input files

You can use this information to decide how to display the data. For example, if the marker is , you put the line both in the left and right widgets. If it's + , you could put a blank line on the left and the actual line on the right showing that the line is unique to the text on the right. Likewise, - means the line is unique to the left.

For example, you can create two text widgets t1 and t2, one for the left and one for the right. You can compare two files by creating a list of lines for each and then passing them to the compare method of the differ and then iterating over the results.

t1 = tk.Text(...)
t2 = tk.Text(...)

f1 = open("file1.txt", "r").readlines()
f2 = open("file2.txt", "r").readlines()

differ = difflib.Differ()
for line in differ.compare(f1, f2):
    marker = line[0]
    if marker == " ":
        # line is same in both
        t1.insert("end", line[2:])
        t2.insert("end", line[2:])

    elif marker == "-":
        # line is only on the left
        t1.insert("end", line[2:])
        t2.insert("end", "\n")

    elif marker == "+":
        # line is only on the right
        t1.insert("end", "\n")
        t2.insert("end", line[2:])

The above code ignores lines with the marker ? since those are extra lines that attempt to bring attention to the different characters on the previous line and aren't actually part of either file. You could use that information to highlight the individual characters if you wish.

Answer from Bryan Oakley on Stack Overflow
Top answer
1 of 4
3

You can use difflib.Differ to return a single sequence of lines with a marker at the start of each line which describes the line. The markers tell you the following information about the line:

Marker Description
'- ' line unique to file 1
'+ ' line unique to file 2
' ' line common to both files
'? ' line not present in either input files

You can use this information to decide how to display the data. For example, if the marker is , you put the line both in the left and right widgets. If it's + , you could put a blank line on the left and the actual line on the right showing that the line is unique to the text on the right. Likewise, - means the line is unique to the left.

For example, you can create two text widgets t1 and t2, one for the left and one for the right. You can compare two files by creating a list of lines for each and then passing them to the compare method of the differ and then iterating over the results.

t1 = tk.Text(...)
t2 = tk.Text(...)

f1 = open("file1.txt", "r").readlines()
f2 = open("file2.txt", "r").readlines()

differ = difflib.Differ()
for line in differ.compare(f1, f2):
    marker = line[0]
    if marker == " ":
        # line is same in both
        t1.insert("end", line[2:])
        t2.insert("end", line[2:])

    elif marker == "-":
        # line is only on the left
        t1.insert("end", line[2:])
        t2.insert("end", "\n")

    elif marker == "+":
        # line is only on the right
        t1.insert("end", "\n")
        t2.insert("end", line[2:])

The above code ignores lines with the marker ? since those are extra lines that attempt to bring attention to the different characters on the previous line and aren't actually part of either file. You could use that information to highlight the individual characters if you wish.

2 of 4
3

Building on @Bryan Oakley's answer, I wrote a quick Gist:

https://gist.github.com/jlumbroso/3ef433b4402b4f157728920a66cc15ed

with a side-by-side diff method (including the method to produce this side-by-side arrangement using the textwrap library) that you can call on two lists of lines:

print(better_diff(
    ["a", "c",      "a", "a", "a", "a",      "a", "a", "e"],
    ["a", "c", "b", "a", "a", "a", "a", "d", "a", "a"],
    width=20,
    as_string=True,
    left_title="  LEFT",
))

will produce:

  LEFT   | 
-------- | --------
a        | a
c        | c
         | b
a        | a
a        | a
a        | a
a        | a
         | d
a        | a
a        | a
e        | 
🌐
PyPI
pypi.org › project › ydiff
ydiff · PyPI
Read log with changes in a Git/Mercurial/Svn workspace (output from e.g. git log -p, svn log --diff), note –diff option is new in svn 1.7.0: cd proj-workspace ydiff -l # read log along with changes, side by side ydiff -lu # equivalent to ydiff -l -u, unified mode ydiff -l -w90 --no-wrap # set text width 90 and disable wrapping ydiff -l file1 dir2 # see log with changes of given files/dirs only
      » pip install ydiff
    
Published   Dec 06, 2025
Version   1.5
Discussions

Side by side diff of large files - Unix & Linux Stack Exchange
diff -y or sdiff - This outputs side-by-side but it outputs the entire file - not just the changes, so they are impossible to find. icdiff - Just too slow (it's written in Python so no surprise there). More on unix.stackexchange.com
🌐 unix.stackexchange.com
July 27, 2018
Compare two files report difference in python - Stack Overflow
Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow. Let’s... 33 Python : Compare two csv files and print out differences More on stackoverflow.com
🌐 stackoverflow.com
Compare two files
If you are on Linux you could do this very easily with the diff command: https://www.geeksforgeeks.org/diff-command-linux-examples/ Otherwise you could read both files in, and use zip() to iterate over them at the same time. More on reddit.com
🌐 r/learnpython
9
3
March 27, 2021
Comparing 2 files with python
I'd use difflib.Differ , like so: import difflib with open('text1.txt') as text1: with open('text2.txt') as text2: d = difflib.Differ() diff = list(d.compare(text1.readlines(), text2.readlines())) with open('diff.txt', 'w') as diff_file: _diff = ''.join(diff) diff_file.write(_diff) If a line starts with '-', it only exists in text1.txt, if it starts with '+' it only exists in text2.txt, and ' ' means that it exists in both. More on reddit.com
🌐 r/learnpython
9
16
July 30, 2015
🌐
Python
docs.python.org › 3 › library › difflib.html
difflib — Helpers for computing deltas
Lines beginning with ‘?’ attempt to guide the eye to intraline differences, and were not present in either input sequence. These lines can be confusing if the sequences contain whitespace characters, such as spaces, tabs or line breaks. ... This class can be used to create an HTML table (or a complete HTML file containing the table) showing a side by side, line by line comparison of text with inter-line and intra-line change highlights.
🌐
TextCompare
textcompare.org › python
Online Python Compare Tool
Find difference between 2 text files. Just input or paste original and modified text and click Compare button. Fast, Private & Unlimited. ... Copy the modified Python in the right block. Just click Compare button to view side by side comparison.
🌐
GitHub
github.com › wagoodman › diff2HtmlCompare
GitHub - wagoodman/diff2HtmlCompare: Side-by-side diff shown in HTML
A python script that takes two files and compares the differences between them (side-by-side) in an HTML format.
Starred by 149 users
Forked by 56 users
Languages   Python 100.0% | Python 100.0%
🌐
PyPI
pypi.org › project › cdiff
cdiff · PyPI
$ cdiff -h Usage: cdiff [options] [file|dir ...] View colored, incremental diff in a workspace or from stdin, with side by side and auto pager support Options: --version show program's version number and exit -h, --help show this help message and exit -s, --side-by-side enable side-by-side mode -w N, --width=N set text width for side-by-side mode, 0 for auto detection, default is 80 -l, --log show log with changes from revision control -c M, --color=M colorize mode 'auto' (default), 'always', or 'never' Note: Option parser will stop on first unknown option and pass them down to underneath revision control.
      » pip install cdiff
    
Published   Dec 31, 2016
Version   1.0
Find elsewhere
🌐
Python
docs.python.org › 3 › library › filecmp.html
filecmp — File and Directory Comparisons
Files and subdirectories in b, filtered by hide and ignore. ... Files and subdirectories in both a and b. ... Files and subdirectories only in a. ... Files and subdirectories only in b. ... Subdirectories in both a and b. ... Files in both a and b. ... Names in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error.
🌐
TestDriven.io
testdriven.io › tips › 43480c4e-72db-4728-8afd-0b0f4f42d4f4
Tips and Tricks - Python - comparing two text files with difflib.HtmlDiff() | TestDriven.io
You can use HtmlDiff to generate an HTML table that shows a side by side, line by line comparison of the text with inter-line and intra-line change highlights. https://docs.python.org/3/library/difflib.html#difflib.HtmlDiff ... import difflib ...
🌐
JetBrains
jetbrains.com › help › pycharm › comparing-files-and-folders.html
Compare files, folders, and text sources | PyCharm Documentation
December 9, 2025 - You can swap sides in the Diff Viewer by pressing the icon on the toolbar. ... By default, Diff Viewer opens in an editor tab. You can configure the settings to open the viewer in a separate window instead.
Top answer
1 of 5
102
import difflib

lines1 = '''
dog
cat
bird
buffalo
gophers
hound
horse
'''.strip().splitlines()

lines2 = '''
cat
dog
bird
buffalo
gopher
horse
mouse
'''.strip().splitlines()

# Changes:
# swapped positions of cat and dog
# changed gophers to gopher
# removed hound
# added mouse

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''):
    print line

Outputs the following:

--- file1
+++ file2
@@ -1,7 +1,7 @@
+cat
 dog
-cat
 bird
 buffalo
-gophers
-hound
+gopher
 horse
+mouse

This diff gives you context -- surrounding lines to help make it clear how the file is different. You can see "cat" here twice, because it was removed from below "dog" and added above it.

You can use n=0 to remove the context.

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
    print line

Outputting this:

--- file1
+++ file2
@@ -0,0 +1 @@
+cat
@@ -2 +2,0 @@
-cat
@@ -5,2 +5 @@
-gophers
-hound
+gopher
@@ -7,0 +7 @@
+mouse

But now it's full of the "@@" lines telling you the position in the file that has changed. Let's remove the extra lines to make it more readable.

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0):
    for prefix in ('---', '+++', '@@'):
        if line.startswith(prefix):
            break
    else:
        print line

Giving us this output:

+cat
-cat
-gophers
-hound
+gopher
+mouse

Now what do you want it to do? If you ignore all removed lines, then you won't see that "hound" was removed. If you're happy just showing the additions to the file, then you could do this:

diff = difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0)
lines = list(diff)[2:]
added = [line[1:] for line in lines if line[0] == '+']
removed = [line[1:] for line in lines if line[0] == '-']

print 'additions:'
for line in added:
    print line
print
print 'additions, ignoring position'
for line in added:
    if line not in removed:
        print line

Outputting:

additions:
cat
gopher
mouse

additions, ignoring position:
gopher
mouse

You can probably tell by now that there are various ways to "print the differences" of two files, so you will need to be very specific if you want more help.

2 of 5
21

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])
🌐
Skeptric
skeptric.com › python-diffs
skeptric - Showing Side-by-Side Diffs in Jupyter
April 12, 2020 - def align_seqs(a: TokenList, b: TokenList, fill:Token='') -> Tuple[TokenList, TokenList]: out_a, out_b = [], [] seqmatcher = difflib.SequenceMatcher(a=a, b=b, autojunk=False) for tag, a0, a1, b0, b1 in seqmatcher.get_opcodes(): delta = (a1 - a0) - (b1 - b0) out_a += a[a0:a1] + [fill] * max(-delta, 0) out_b += b[b0:b1] + [fill] * max(delta, 0) assert len(out_a) == len(out_b) return out_a, out_b · When we have aligned sentences we can use CSS to display two sequences side by side.
🌐
GeeksforGeeks
geeksforgeeks.org › python › compare-two-files-line-by-line-in-python
Compare two Files line by line in Python - GeeksforGeeks
March 21, 2024 - Python has a Module which is specially used for comparing the differences between the files. To get differences using the difflib library, we have to call the unified_diff() function to this comparison.
🌐
Reddit
reddit.com › r/learnpython › compare two files
r/learnpython on Reddit: Compare two files
March 27, 2021 -

I would like to compare two files with each other and show the differences. There are so many examples when you google this but I can't quite find what I am looking for. My two files with be very similar, but a line or two different (added, or removed) All I want is to compare the two files and show lines that are added with a + and lines that have been removed with a -

So two file A and B, A is the original file and B is the new file. So if lines have been added or removed from B then show the lines added or removed with a + or a -.

I'm writing a script that checks a device configuration every day and if it's changed from the day before then show what has been added/removed.

Thank you

🌐
Florian-dahlitz
florian-dahlitz.de › articles › create-your-own-diff-tool-using-python
Create Your Own Diff-Tool Using Python - Florian Dahlitz
So far, we build a simple diff-tool by turning your short script from the beginning into a command-line tool - cool! Now, we will add some more lines to support HTML output. The difflib module provides an HtmlDiff class, which can be used to create an HTML table (or a complete HTML file containing the table) showing a side by side, line by line comparison of text with inter-line and intra-line change highlights.
🌐
DEV Community
dev.to › _d7eb1c1703182e3ce1782 › diff-checker-online-compare-files-and-text-side-by-side-7hb
Diff Checker Online — Compare Files and Text Side by Side - DEV Community
1 week ago - DevPlaybook Code Diff — Side-by-side comparison with syntax highlighting for JavaScript, Python, JSON, YAML, and more.
🌐
TutorialsPoint
tutorialspoint.com › how-to-find-difference-between-2-files-in-python
How to find difference between 2 files in Python?
May 15, 2025 - Following are the key methods which are used to compare two files in python - Line-by-line comparison: This is a straightforward approach to textual differences.