Python FileCmp

filecmp is a module for comparing files.


Usage

Clear_Cache

Clear the filecmp.cmp cache.


Cmp

Compare two files. By default a shallow comparison is used (checking type, size, and modification time). To use a deep comparison, try:

import filecmp

filecmp.cmp(fn1, fn2, shallow=False)

Results are cached. If the shallow comparison keys (see above) have not changed, the cached results are used.

The function takes file names, not file objects.


CmpFiles

Compare a list of files in two directories. Returns three lists:

Note that a file not existing in one directory or the other counts as an error, not a mismatch.

For example:

import filecmp

filecmp.cmpfiles('/etc/skel', '/home/somebody', ['.profile', '.bashrc'])

There is a shallow named option with the same effect as in filecmp.cmp.


DirCmp

A class for comparing two directories. All comparisons are shallow.

import filecmp

filecmp.dircmp(d1, d2)

The returned object has a variety of properties that can be used for customized reporting.

Property Name

Value

left

names in d1

right

names in d2

left_list

names in d1 filtered by hide and ignore

right_list

names in d2 filtered by hide and ignore

common

names in both d1 and d2

left_only

names in d1 and not d2

right_only

names in d2 and not d1

common_dirs

subdirectory names in both d1 and d2

common_files

filenames in both d1 and d2

common_funny

filenames in both d1 and d2 but either have different file types or raised an error on examining for file type

same_files

filenames that match

diff_files

filenames that did not match

funny_files

filenames in both d1 and d2 but could not be compared, usually for an error that isn't applicable to common_funny

subdirs

mapping of common_dirs names to filecmp.dircmp instances

The named options ignore and hide are used for filtering some of the above properties. They default to filecmp.DEFAULT_IGNORES and ['.', '..'] by default.

import filecmp

dcmp = filecmp.dircmp('/etc/skel', '/home/somebody') 

for name in dcmp.diff_files:
    print("diff_file %s found in %s and %s" % (name, dcmp.left, dcmp.right))

for sub_dcmp in dcmp.subdirs.values():
    print_diff_files(sub_dcmp)


See also

Python filecmp module documentation

Python Module of the Day article for filecmp


CategoryRicottone

Python/FileCmp (last edited 2023-06-15 18:35:09 by DominicRicottone)