LoginSignup
7
6

More than 3 years have passed since last update.

PythonでDiff

Last updated at Posted at 2019-03-11

 比較用の関数を作成

FileDiff.py
import difflib


def diff(file_name1, file_name2):
    f1 = open(file_name1, 'r')
    f2 = open(file_name2, 'r')
    d = difflib.Differ()
    diff = d.compare(f1.readlines(), f2.readlines())
    return '\n'.join(diff)

 サンプルコード

import os
import FileDiff

working_dir = r'C:\temp'
file1_name = 'diff_test01.txt'
file2_name = 'diff_test02.txt'

os.chdir(working_dir)

print(FileDiff.diff(file1_name, file2_name))

 テストファイル

diff_test01.txt
Mike is a good student!
Mike plays street fighters.
Mike plays soccer.
diff_test02.txt
Mike is a good student!
Addis plays king of fighters.
Mike plays socer.

 実行結果

  Mike is a good student!

- Mike plays street fighters.

+ Addis plays king of fighters.

- Mike plays soccer.
?               -

+ Mike plays socer.

ファイル以外のもの(各タイプを持っている内部関数など)を比較することも可能

import difflib
l = dir(list)
t = dir(tuple)
d = difflib.Differ()
diff = d.compare(l, t)
print('\n'.join(diff))

実行結果

  __add__
  __class__
  __contains__
  __delattr__
- __delitem__
  __dir__
  __doc__
  __eq__
  __format__
  __ge__
  __getattribute__
  __getitem__
+ __getnewargs__
  __gt__
  __hash__
- __iadd__
- __imul__
  __init__
  __init_subclass__
  __iter__
  __le__
  __len__
  __lt__
  __mul__
  __ne__
  __new__
  __reduce__
  __reduce_ex__
  __repr__
- __reversed__
  __rmul__
  __setattr__
- __setitem__
  __sizeof__
  __str__
  __subclasshook__
- append
- clear
- copy
  count
- extend
  index
- insert
- pop
- remove
- reverse
- sort
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6