Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 67,989 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 67,989 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 67,989 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!