[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

and directories that exist only in the other. Something more custom and recursive seems
in order here.


Finding Directory Differences


Before we start coding, the first thing we need to clarify is what it means to compare
two directory trees. If both trees have exactly the same branch structure and depth, this
problem reduces to comparing corresponding files in each tree. In general, though, the
trees can have arbitrarily different shapes, depths, and so on.


More generally, the contents of a directory in one tree may have more or fewer entries
than the corresponding directory in the other tree. If those differing contents are file-
names, there is no corresponding file to compare with; if they are directory names, there
is no corresponding branch to descend through. In fact, the only way to detect files and
directories that appear in one tree but not the other is to detect differences in each level’s
directory.


In other words, a tree comparison algorithm will also have to perform directory com-
parisons along the way. Because this is a nested and simpler operation, let’s start by
coding and debugging a single-directory comparison of filenames in Example 6-11.


Example 6-11. PP4E\System\Filetools\dirdiff.py


"""
################################################################################
Usage: python dirdiff.py dir1-path dir2-path
Compare two directories to find files that exist in one but not the other.
This version uses the os.listdir function and list difference. Note that
this script checks only filenames, not file contents--see diffall.py for an
extension that does the latter by comparing .read() results.
################################################################################
"""


import os, sys


def reportdiffs(unique1, unique2, dir1, dir2):
"""
Generate diffs report for one dir: part of comparedirs output
"""
if not (unique1 or unique2):
print('Directory lists are identical')
else:
if unique1:
print('Files unique to', dir1)
for file in unique1:
print('...', file)
if unique2:
print('Files unique to', dir2)
for file in unique2:
print('...', file)


def difference(seq1, seq2):


Comparing Directory Trees | 309
Free download pdf