Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Ralph Langdon
Ralph Langdon
721 Points

Playing around with Hashlib

Hey guys I am in the intro to Python course and have started playing around with HashLib. Here is my program

import hashlib
import os

"""
    Program to get a hash for a specified
    file in currentworking directory. 
"""

print(os.getcwd())

def md5sum(filename):
     hash = hashlib.md5()
     return hash.hexdigest()

filename ='f1.py'
mysum = md5sum(filename)

print(mysum)

It is creating a hash for the file f1.py in the current working directory. For some reason when I add new data to the file the Hash does not change. My expectation is that the hash should be different if I had data to the file. Like a checksum. Is this expection incorrect?

Here is the output before 
/Users/jlangdon/PycharmProjects/untitled

d41d8cd98f00b204e9800998ecf8427e

Process finished with exit code 0

Then I added new lines to the file and the hash was the same????

Chris Freeman
Chris Freeman
Treehouse Moderator 68,460 Points

Where are you using the argument filename in your function:

def md5sum(filename):
     hash = hashlib.md5()
     return hash.hexdigest()
Chris Freeman
Chris Freeman
Treehouse Moderator 68,460 Points

Also, where are you opening the file "f1.py" to read. It looks like you are trying to hash the string "f1.py"

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,460 Points

I've tweaked your code a bit:

def md5sum(filename):
    hash = hashlib.md5(filename.read())
    return hash.hexdigest()

with open('f1.py') as filename:
    mysum = md5sum(filename)

print(mysum)
Ralph Langdon
Ralph Langdon
721 Points

Fantastic! "With Open" and filename.read are new concepts to me. I will take a look at those. It is nice to have a message board where beginners can post without being snarked at for silly code. Thanks!