python - 比较列表中的文件

标签 python python-2.7

我有一个文件路径列表。对于每个列表元素,我添加两个字符串 A 和 B,以便文件的绝对路径为:file1=A+listelemet 和 file2=B+listelement。我需要检查文件是否相同。如果相同,则忽略。如果不相同,则打印行号并显示给定行号的这些行的比较。

我尝试过这样的事情:

with open(file1, 'r') as filea:
    with open(file2, 'r') as fileb:
        diff = difflib.unified_diff(filea.readlines(),fileb.readlines(),fromfile=os.path.basename(file1),tofile=os.path.basename(file2))
        for line in diff:
            sys.stdout.write(line)

但它不会为两个文件中不同的每个行号提供统一的输出

假设我有一个文本文件:

a
s
s
s
d





ssasa

另一个内容如下:

a
s
d
ere

ewrwer

werewr

我得到的输出为:

--- asd.txt
+++ asd1.txt
@@ -1,11 +1,8 @@
 a
 s
-s
-s
 d
+ere

+ewrwer

-
-
-
-ssasa+werewr

但是,我需要打印行号的输出,然后是每个文件的该行的差异

控制台中所需的输出:

Comparing files file1 and file2


    3:  file1:s,file2:d
    4:  file1:s, file2:ere
    5:  file1:d
    6:  file2:ewrwer
    8:  file2:werewr
   11:  file1:ssasa

最佳答案

考虑到您想要的输出,您可能更喜欢使用 filecmp 和以下函数:

import filecmp
from itertools import izip_longest

def file_differences(file1, file2):
    with open(file1, 'r') as f1, open(file2, 'r') as f2:
        for i, lines in enumerate(izip_longest(f1.readlines(), f2.readlines(), fillvalue='')):
            lines = map(lambda s: s.rstrip(), lines)
            if lines[0] != lines[1]:
                out = []
                for f, line in zip((file1, file2), lines):
                    s = f + ': ' + line if line else ''
                    out.append(s)
                sep = ', ' if out[0] and out[1] else ''
                string = out[0] + sep + out[1]
                print('{0}: {1}'.format(i+1, string))


if not filecmp.cmp('file1.txt', 'file2.txt'):
    file_differences('file1.txt', 'file2.txt')

关于python - 比较列表中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50230377/

相关文章:

python - Scrapy Spiders - 处理非 HTML 链接(PDF、PPT 等)

python - 在 Python 2.7 中将 ½ 解析为 0.5

python - MongoDB - 不存在字段的错误处理

python - Python 中的模式替换

python - 使用.format和变量的python字符串格式化

python - Excel 工作表到 Numpy 数组

python - 如何从已分割的 .txt 文件中获取多行并将它们保存到不同的变量中

python - 拉力赛Python API

python - Python 中的递归 SFTP listdir?

python - 将数据帧转换为长的、保留索引的列