How in Python check if two files ( String and file ) have same content?
Question: I am very new to Python and have question. How in Python check if two files (
String and file ) have same content ? I need to download some stuffs and
rename, but I don't want to save same stuff with two or more different names
(same stuff can be on different ip addresses ).


Answer: If the file is large, I would consider reading it in chunks like this:

compare.py:

    
    
    import hashlib
    
    teststr = "foo"
    filename = "file.txt"
    
    def md5_for_file(f, block_size=2**20):
        md5 = hashlib.md5()
        while True:
            data = f.read(block_size)
            if not data:
                break
            md5.update(data.encode('utf8'))
        return md5.digest()
    
    
    md5 = hashlib.md5()
    md5.update((teststr + "\n").encode('utf8'))
    digest = md5.digest()
    f = open(filename, 'r')
    print(md5_for_file(f) == digest)
    

file.txt:

    
    
    foo
    

This program prints True if the string and file match

