giving garbage value while trying to store a md5 hash in a file in python
m=md5.new()
a=10111011
>>> m.update(str(a))
>&g开发者_Python百科t;> 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 ..
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')
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.
精彩评论