Module filecmp

The module filecmp provides functions for file and directory comparisons. The method cmp(filel, file2[, shallow]) will compare filel with file2. If shallow is not provided (or is True), files that have the same stat signature are considered equal. By this I mean files that have the same system information such as size, creation date, and more (see http://docs. for an explanation of stat). If shallow is False, files are also compared for content.

>>> filenames = ['../data/filel.bin', '../data/file2.bin']

>>> import filecmp

>>> filecmp.cmp(filenames[o], filenames[l]) True

The class dircmp(dirl, dir2) enables the comparison of directories dirl and dir2. The comparison includes all subdirectories as well. The method report() will print the result from comparing both directories.

For the following example, I assume you've created the file files.tar.bz2 in the previous compression example. Here, we'll create two directories, newl and new2. Directory newl will contain the extracted files from the archive; directory new2 will contain the extracted files from the archive as well as another subdirectory, new3, which will also contain the contents of the archive. We'll compare the directory contents (see Listing 10-15).

Listing 10-15. Comparing Directories import tarfile, os, filecmp if not os.path.exists('newl'):

os.mkdir('newl') if not os.path.exists('new2/new3'): os.makedirs('new2/new3')





The results are as follows:

diff newl new2

Identical files : ['file0.txt', 'filel.txt', 'file2.txt', 'file3.txt', 'file4.txt']

As you can see, comparing directory contents using the filecmp module is easy and simple.

Was this article helpful?

0 0

Post a comment