Search code examples
pythonhashfile-iohashmaphashtable

Hash each line in Text file Python MD5


I'm trying to write a program which will open a text file and give me an md5 hash for each line of text. For example I have a text file with:

66090001081992
66109801042010
68340016052015
68450001062015
79450001062016

This is my code:

import hashlib
hasher = hashlib.md5()
archivo_empleados = open("empleados.txt","rb")
lista = (archivo_empleados.readlines())



archivo_empleados.close()

Solution

  • You could open the file with a with context manager(don't need to call .close()), then iterate each line of the file with a for loop and print the MD5 hash string. You also need to encode in utf-8 before hashing.

    import hashlib
    
    def compute_MD5_hash(string, encoding='utf-8'):
        md5_hasher = hashlib.md5()
        md5_hasher.update(string.encode(encoding))
        return md5_hasher.hexdigest()
    
    with open("path/to/file") as f:
        for line in f:
            print(compute_MD5_hash(line))
    

    Which gives hash strings like the following:

    58d3ab1af1afd247a90b046d4fefa330
    6dea9449f52e07bae45a9c1ed6a03bbc
    9e2d8de8f8b3df8a7078b8dc12bb3e35
    20819f8084927f700bd58cb8108aabcd
    620596810c149a5bc86762d2e1924074
    

    You can have a look at the various hashlib functions in the documentation.