Fonction pratique pour écrire un tableau d'int dans un fichier,
def write_array(fname,ray):
'''
fname is a file pathname
ray is an array of int
'''
print("write:",fname)
EncodeInit()
buffer = [ encode(z) for z in ray ]
some = bytearray(buffer)
immutable = bytes(some)
with open(fname,"wb") as bfh:
wc = bfh.write(immutable)
print("wrote:",wrote)
return wc
Comment appeler la fonction,
write_array("data/filename",[1,2,3,4,5,6,7,8])
Et enveloppez ce qui suit dans une classe pour un codage/décodage lisible :
Encode = {}
Decode = {}
def EncodeInit():
'''
Encode[] 0:62 as 0-9A-Za-z
Decode[] 0-9A-Za-z as 0:62
'''
for ix in range( 0,10): Encode[ix] = ix+ord('0')
for ix in range(10,36): Encode[ix] = (ix-10)+ord('A')
for ix in range(36,62): Encode[ix] = (ix-36)+ord('a')
for ix in range( 0,10): Decode[ix+ord('0')] = ix
for ix in range(10,36): Decode[(ix-10)+ord('A')] = ix
for ix in range(36,62): Decode[(ix-36)+ord('a')] = ix
def encode(x):
'''
Encode[] 0:62 as 0-9A-Za-z
Otherwise '.'
'''
if x in Encode: return Encode[x]
# else: error
return ord('.')
def decode(x):
'''
Decode[] 0-9A-Za-z as 0:62
Otherwise -1
'''
if x in Decode: return Decode[x]
# else: error
return -1