Search code examples
pythonubuntumd5sum

md5sum of a file without file name assigning to a variable in python


I'm trying to assign the md5 sum of a file (in ubuntu) to a variable(any) in python script as below

aList=subprocess.check_output(["md5sum",filename])

i want to assign only sum to the variable for that i used below code but it's not working

aList=subprocess.check_output(["md5sum",filename," | awk '{print $1}'"])

please help me to find out solution

thanks in advance


Solution

  • Rather than shelling out to perform the md5sum, use Python's inbuilt hashlib.md5 implementation:

    import hashlib
    
    with open(filename, 'rb') as f:
        hexdigest = hashlib.md5(f.read()).hexdigest()
        print(hexdigest)