为什么此目录比较程序无法检测到多余的文件?

时间:2018-07-21 08:41:53

标签: python

我有一个目录比较程序(基于文档https://docs.python.org/3/library/filecmp.html中给出的示例),该程序找不到要放在子目录中进行测试的额外文件。该程序是:

import sys
from filecmp import dircmp

def print_diff_files(dcmp):
    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)

dcmp = dircmp(sys.argv[1], sys.argv[2]) 
print_diff_files(dcmp)
print(dcmp.left_only)
print(dcmp.right_only)

right_only列表中应该包含某些内容,只是[]。为什么会这样?

2 个答案:

答案 0 :(得分:1)

我对blhsing的程序进行了较小的更改,如下所示:

#diffdir.py - compares directories and lists shallow differences; use python3
import sys
from filecmp import dircmp

def print_diff_files(dcmp):
    for name in dcmp.diff_files:
        print("\nDiff file: %s found in %s and %s" % (name, dcmp.left, dcmp.right))
    for sub_dcmp in dcmp.subdirs.values():
        print_diff_files(sub_dcmp)
    if dcmp.left_only:
        print("\nLeft only:", dcmp.left_only)
    if dcmp.right_only:
        print("\nRight only:", dcmp.right_only)

dcmp = dircmp(sys.argv[1], sys.argv[2]) 
print_diff_files(dcmp)
print()

答案 1 :(得分:0)

filecmp.dircmp不会递归比较文件。如果您想让dircmp.left_onlydircmp.right_only递归,则必须像dircmp.diff_files那样自己做。

print(dcmp.left_only)print(dcmp.right_only)移动到递归函数print_diff_files中:

import sys
from filecmp import dircmp

def print_diff_files(dcmp):
    for name in dcmp.diff_files:
        print("diff_file %s found in %s and %s" % (name, dcmp.left, dcmp.right))
    if dcmp.left_only:
        print('%s: %s ' % (dcmp.left, dcmp.left_only))
    if dcmp.right_only:
        print('%s: %s ' % (dcmp.right, dcmp.right_only))
    for sub_dcmp in dcmp.subdirs.values():
        print_diff_files(sub_dcmp)

dcmp = dircmp(r'c:\temp\t', r'c:\temp\s')
print_diff_files(dcmp)