Convert to binary and convert back to strings

Jussi Salmela tiedon_jano at hotmail.com
Thu Feb 22 03:16:21 EST 2007


Harlin Seritt kirjoitti:
> Hi...
> 
> I would like to take a string like 'supercalifragilisticexpialidocius'
> and write it to a file in binary forms -- this way a user cannot read
> the string in case they were try to open in something like ascii text
> editor. I'd also like to be able to read the binary formed data back
> into string format so that it shows the original value. Is there any
> way to do this in Python?
> 
> Thanks!
> 
> Harlin
> 

Here's my suggestion using compression. Seems to work, but a word of 
warning: I've never used the codecs explicitly before!

#==============
# -*- coding: cp1252 -*-
import codecs

s = 'This is so secret that it must be hidden åäö€'
print s
f = codecs.open('secret.txt', 'wb', 'zlib_codec')
f.write(s)
f.close()

f = codecs.open('secret.txt', 'rb', 'zlib_codec')
s2 = f.read()
f.close()
print s2
if s == s2: print 'OK'
else: print '!"#¤%%'
#================



More information about the Python-list mailing list