You do not need to define a function with 5-20 lines of code to do this! Save your time by using the pathlib and hashlib libraries, also py_essentials is another solution, but third-parties are *****.
from pathlib import Path import hashlib filepath = '/path/to/file' filebytes = Path(filepath).read_bytes() filehash_sha1 = hashlib.sha1(filebytes) filehash_md5 = hashlib.md5(filebytes) print(f'MD5: {filehash_md5}') print(f'SHA1: {filehash_sha1}')
I used a few variables here to show the steps, you know how to avoid it.
What do you think about the below function?
from pathlib import Path import hashlib def compute_filehash(filepath: str, hashtype: str) -> str: """Computes the requested hash for the given file. Args: filepath: The path to the file to compute the hash for. hashtype: The hash type to compute. Available hash types: md5, sha1, sha224, sha256, sha384, sha512, sha3_224, sha3_256, sha3_384, sha3_512, shake_128, shake_256 Returns: A string that represents the hash. Raises: ValueError: If the hash type is not supported. """ if hashtype not in ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'shake_128', 'shake_256']: raise ValueError(f'Hash type {hashtype} is not supported.') return getattr(hashlib, hashtype)( Path(filepath).read_bytes()).hexdigest()
file.read()does - read the entire file.