tags:

views:

63

answers:

2
m=md5.new() 
a=10111011
>>> m.update(str(a))
>>> k=m.digest()
>>> k
'\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M'
>>> f.write(str(k))
>>> f.flush()

the file f is filled with garbage value which i cant use to read again for further use of the hash . Why does it give the garbage value when on the python terminal it gives proper output?And the worst part is file goes corrupt ..

+1  A: 

One possibility is that you're on Windows and haven't properly opened the file in binary mode, i.e., as 'wb'. We can't tell, since you don't show us how you opened f.

Another possibility might be that you're on Python 3 (where str means unicode), but I think in that case you'd see a leading b when you show k (and there's no md5 module in Python 3's standard library).

Opening the file the right way, with Python 2.6.4 on a Mac, I see the digest as

'\x82s\xf9\xa4\x83\x04\x87\xd0\xfdg\xee\xfa\x1f\x05B>'

both as k and as the file's contents. I don't know why you're seeing something that different, by the way; I get the same result with Python 2.4 and 2.5.

Alex Martelli
i am on linux using python 2.6 ..
mekasperasky
Now trying on Linux I get the same identical result as in my answer, both for `k` and the file's contents -- i.e., your problem just can't be reproduced. Try making a complete, self-contained script (including the opening and closing of the file) to reproduce your problem, and edit your question to show such a self-contained reproduction of the problem, rather than an incomplete fragment which (per se, assuming all surrounding code is right) exhibits no errors.
Alex Martelli
as you can see in the code that i have given . i have typed it in the python terminal . so its very much the condensed version .. what ouput i am getting is this �ZV�a�e젳|�����1�e��Y��6���Meven though i change it to wb ..
mekasperasky
Congratulations to the 100k! :-)
kaizer.se
+2  A: 

If you want further clues where your "garbage" (your digest!) is coming from, try print k versus print repr(k)!

You have a raw byte string. I think you want to insert a hexdigest instead? Either use k = m.hexdigest() or k = repr(m.digest()) and write that to your file.

Basically, you can choose your representation, choose what you write to your file. Which of these do you want to see?

>>> print k
�1���Y�6���M
>>> print repr(k)
'\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M'
>>> print k.encode("hex")
ec9d31896508a1c259f6bf36fee4e24d

Pass exactly the same to f.write(..) as you do to print. As you can see, in the original version you used 'k' ('str(k)' is the same as just 'k')

kaizer.se