我应该用struct比较字节吗?

3 投票
2 回答
580 浏览
提问于 2025-04-16 02:47

我正在尝试比较两个文件中的数据,并找出它们不同的地方。 我在一些文本文件上试过,效果还不错。 但是在一些非文本文件上(虽然里面也有ASCII文本),我称它们为二进制数据文件(比如可执行文件等)。

它似乎认为某些字节是相同的,尽管我在十六进制编辑器中查看时,明显不是。我尝试打印出它认为相同的这些二进制数据,但得到的却是空白行,应该打印的内容没有显示出来。 所以,我觉得这可能是问题的根源。

那么,比较可能是二进制数据和包含ASCII文本的数据的最佳方法是什么呢?我觉得使用结构模块可能是一个起点……

正如你在下面看到的,我用==运算符来比较字节。

这是代码:

import os
import math


#file1 = 'file1.txt'
#file2 = 'file2.txt'
file1 = 'file1.exe'
file2 = 'file2.exe'
file1size = os.path.getsize(file1)
file2size = os.path.getsize(file2)
a = file1size - file2size
end = file1size  #if they are both same size
if a > 0:
    #file 2 is smallest
    end = file2size
    big = file1size

elif a < 0:
    #file 1 is smallest
    end = file1size
    big = file2size


f1 = open(file1, 'rb')
f2 = open(file2, 'rb')



readSize = 500
r = readSize
off = 0
data = []
looking = False
d = open('data.txt', 'w')


while off < end:
    f1.seek(off)
    f2.seek(off)
    b1, b2 = f1.read(r), f2.read(r)
    same = b1 == b2
    print ''
    if same:
        print 'Same at: '+str(off)
        print 'readSize: '+str(r)
        print b1
        print b2
        print ''
        #save offsets of the section of "different" bytes
        #data.append([diffOff, diffOff+off-1])  #[begin diff off, end diff off]
        if looking:
            d.write(str(diffOff)+" => "+str(diffOff+off-2)+"\n")
            looking = False
            r = readSize
            off = off + 1
        else:
            off = off + r

    else:
        if r == 1:
            looking = True
            diffOff = off
            off = off + 1 #continue reading 1 at a time, until u find a same reading
        r = 1  #it will shoot back to the last off, since we didn't increment it here



d.close()
f1.close()
f2.close()          

#add the diff ending portion to diff data offs, if 1 file is longer than the other
a = int(math.fabs(a))  #get abs val of diff
if a:
    data.append([big-a, big-1])


print data

2 个回答

0

你可能遇到了编码和解码的问题。有人可能会给出更好的解决办法,但你可以试着把文件读成一个 bytearray,这样你就能读取原始的字节,而不是解码后的字符:

下面是一个简单的例子:

$ od -Ax -tx1 /tmp/aa
000000 e0 b2 aa 0a
$ od -Ax -tx1 /tmp/bb
000000 e0 b2 bb 0a

$ cat /tmp/diff.py 
a = bytearray(open('/tmp/aa', 'rb').read())
b = bytearray(open('/tmp/bb', 'rb').read())
print "%02x, %02x" % (a[2], a[3])
print "%02x, %02x" % (b[2], b[3])

$ python /tmp/diff.py 
aa, 0a
bb, 0a
4

你试过 difflibfilecmp 这两个模块吗?

这个模块提供了一些类和函数,用来比较序列。比如说,它可以用来比较文件,并且可以以多种格式输出差异信息,包括HTML格式和上下文、统一的差异格式。如果你想比较文件夹和文件,也可以看看 filecmp 模块。

filecmp模块定义了一些函数,用来比较文件和文件夹,提供了不同的时间和准确性选择。如果你想比较文件,也可以参考 difflib 模块。

.

撰写回答