pythonfunctionfileftpcompare

[Python]Function that compares two zip files, one located in FTP dir, the other on my local machine


I have an issue creating function that compare two zip files(if they are the same, not only by name). Here is example of my code:

def validate_zip_files(self):
    host = '192.168.0.1'
    port = 2323
    username = '123'
    password = '123'
    ftp = FTP()
    ftp.connect(host, port)
    ftp.login(username,password)
    ftp.cwd('test')
    print ftp.pwd()
    ftp.retrbinary('RETR test', open('test.zip', 'wb').write)
    file1=open('test.zip', 'wb')
    file2=open('/home/user/file/text.zip', 'wb')
    return filecmp.cmp(file1, file2, shallow=True)

One of the problems is that the second zip is in different location('/home/user/file/text.zip') and i am downloading the zip file in the dir where my python script is. I am not 100% sure that filecmp.cmp works with .zip files.

Any ideas would be great :) Thanks.


Solution

  • Rather than comparing the files directly, I would go ahead and compare hashed values of the files. This eliminates the dependency of filecmp, which might -as you said - not work with zipped files.

    import hashlib
    
    def compare_files(a,b):
        fileA = hashlib.sha256(open(a, 'rb').read()).digest()
        fileB = hashlib.sha256(open(b, 'rb').read()).digest()
        if fileA == fileB:
            return True
        else:
            return False