我应该使用struct来比较字节吗?

3
我正在尝试比较两个文件中的数据,并检索出差异的偏移量列表。我在一些文本文件上尝试了它,效果很不错。但是在非文本文件(仍包含ASCII文本)上,即所谓的二进制数据文件(可执行文件等),似乎会认为某些字节是相同的,即使在十六进制编辑器中查看时,它们显然不是。我尝试打印出它认为相同的二进制数据,但应该打印的位置却出现了空行,因此,我认为这就是问题的根源。那么,有什么最好的方法可以比较既可能是二进制数据又包含ASCII文本的数据字节呢?我想使用struct模块可能是一个起点...如下所示,我使用“==”运算符来比较字节。以下是代码:
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个回答

4

你尝试过使用 difflibfilecmp 模块吗?

该模块提供了用于比较序列的类和函数。例如,它可以用于比较文件,并可以生成各种格式的差异信息,包括HTML和上下文和统一的差异。有关比较目录和文件,请参见 filecmp 模块。

filecmp 模块定义了用于比较文件和目录的函数,具有各种可选的时间/正确性权衡。有关比较文件,请参见 difflib 模块。

.


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接