Python3.7获取两个目录中多个文件的差异性。

问题描述 投票:0回答:1

我被创建这个脚本所需要的基本逻辑卡住了。我试图从本地服务器到远程服务器做一个比较。我有显式文件名的diff代码,但现在我需要确定文件是否相同,这样我在循环浏览目录时就不会在两个完全不同的文件上做diff。我不太明白我需要使用的逻辑。这是我的设置。

source
|- test1.xml
|-- directory
|---- test2.xml
|---- test3.xml

remote
|- test1.xml
|-- directory
|---- test2.xml
|---- test4.xml

我想知道如何查看这些目录 匹配哪些目录的文件名是相同的 然后对相同文件名的目录进行差异分析 所以最终我得到的是

patched
    |- test1.xml
    |-- directory
    |---- test2.xml
    |---- test3.xml
    |---- test4.xml

每一个答案和额外的资源。

files = filecmp.dircmp('../source', '../repo')


def open_file(filename):
    with open(filename) as f:
        lines = f.readlines()
        return lines


def write_to_new_file(filename, result):
    with open(filename, 'w') as f:
        lines = f.write(result)
        return lines


def report_file_diff(dcmp):
    for name in dcmp.diff_files:
        print("DIFF file %s found in %s and %s" % (name,
                                                   dcmp.left, dcmp.right))
        fromfile = os.path.abspath(dcmp.left + '/' + name)
        tofile = os.path.abspath(dcmp.right + '/' + name)
        source = open_file(fromfile)
        repo = open_file(tofile)
        diff = difflib.unified_diff(source, repo, fromfile=fromfile, tofile=tofile, lineterm='\n')
        result = Colorize.color_diff(diff)
        print(''.join(result), end="")
        with open('why_is_this_not_working.txt', 'w') as f:
            f.write('Because you don\'t know what you are doing\n')
            f.write('Because you suck\n')
    for name in dcmp.left_only:
        print("ONLY SOURCE file %s found in %s" % (name, dcmp.left))
    for name in dcmp.right_only:
        print("ONLY REMOTE file %s found in %s" % (name, dcmp.right))
    for sub_dcmp in dcmp.subdirs.values():
        print(sub_dcmp)


report_file_diff(files)
python python-3.x
1个回答
1
投票

你所需要的就是队列。首先将根目录添加到队列中,然后运行一些逻辑如下的代码。

  1. 从队列中弹出项目
  2. 在目的地列出项目(像dir命令)
  3. 在列表中(从第2步开始),有2种类型的对象需要你来处理。
    1. 档案 你可以检查它们是否存在于源中(通过名称或二进制形状(通过哈希值检查))(在源中的位置应该是位置队列。)
    2. 文件夹 将其路径添加到队列中,并从第1步开始重新检查。
  4. 如果任何东西在源码中不存在(无论是在步骤3.1还是3.2中),复制它们(或任何其他你应该做的操作)。
© www.soinside.com 2019 - 2024. All rights reserved.