文件内容打印及文件夹比较的问题

1 投票
1 回答
38 浏览
提问于 2025-04-13 15:10

我正在尝试比较两个文件夹和文件之间的差异。现在它告诉我内容不同,但我希望它能实际打印出那些在另一个文件夹中没有的、同名的文件的具体差异。

我有一个脚本,里面使用了mmap来读取内容。到目前为止,它可以告诉我哪些文件不同,但并没有实际打印出具体的差异。

import os
import mmap

def compare_files(file1: str, file2: str) -> bool:
    """Function to compare files."""

with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
    size1 = f1.seek(0, 2)
    size2 = f2.seek(0, 2)
    if size1 != size2:
        return False
    if size1 == 0:
        return True

    with mmap.mmap(f1.fileno(), 0, access=mmap.ACCESS_READ) as mm1, \
    mmap.mmap(f2.fileno(), 0, access=mmap.ACCESS_READ) as mm2:
        return mm1[0:] == mm2[0:]

def compare_folders(folder1: str, folder2: str) -> None:
    differences_found = False

# Compare files in folder1
for root1, dirs, files in os.walk(folder1):
    for file in files:
        file1 = os.path.join(root1, file)
        root2 = root1.replace(folder1, folder2, 1)
        file2 = os.path.join(root2, file)
        if not os.path.isfile(file2):
            print(f"File {file} exists in {root1} but not in {root2}")
            differences_found = True
        else:
            # If the file exists in both folders, compare them
            if not compare_files(file1, file2):
                print(f"Files {file} differ in {root1} and {root2}")
                differences_found = True

# Compare files in folder2
for root2, dirs, files in os.walk(folder2):
    for file in files:
        root1 = root2.replace(folder2, folder1, 1)
        file1 = os.path.join(root1, file)
        file2 = os.path.join(root2, file)
        if not os.path.isfile(file1):
            print(f"File {file} exists in {root2} but not in {root1}")
            differences_found = True

if not differences_found:
    print("No differences found between the files in the two folders.")

if __name__ == "__main__":
    folder1 = input("Enter path to the first folder: ")
    folder2 = input("Enter path to the second folder: ")

    compare_folders(folder1, folder2)

1 个回答

0

我觉得你是在找 difflib 这个库。

import difflib

def write_difference(file1: str, file2: str) -> str:
    d = difflib.Differ()
    diff = d.compare(file1, file2)
    return '\n'.join(diff)

撰写回答