\$\begingroup\$
\$\endgroup\$
3
I wrote a python function that writes a integer to a file in binary form. But are there any ways that I can reduce the number of steps, is there a more efficient way to write a integer to a file?
def IntWrite(FileName, Integer):
#convert to hexadecimal
data = str('{0:0x}'.format(Integer))
#pad number if odd length
if(len(data) % 2 != 0):
data="0"+data
#split into chucks of two
info = [data[i:i+2] for i in range(0, len(data), 2)]
#convert each chuck to a byte
data2 = "".join([chr(int(a, 16)) for a in info])
#write to file
file(FileName, "wb").write(data2)
#convert back to integer
def IntRead(FileName):
RawData = file(FileName, "rb").read()
HexData = "".join(['{0:0x}'.format(ord(b)) for b in RawData])
return int(HexData, 16)
IntWrite("int_data.txt", 100000)
print IntRead("int_data.txt")
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Nov 13, 2013 at 1:55
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
Python comes with a built-in pickle
module for serialization:
>>> import pickle
>>> with open('data', 'wb') as f: pickle.dump(9 ** 33, f)
>>> with open('data', 'rb') as f: print(pickle.load(f))
30903154382632612361920641803529
(P.S. I wouldn't use a filename ending with .txt
to store binary data.)
answered Nov 13, 2013 at 13:02
-
2\$\begingroup\$ Note that pickle's binary format is incompatible with the original question. \$\endgroup\$200_success– 200_success2013年11月13日 15:51:37 +00:00Commented Nov 13, 2013 at 15:51
-
\$\begingroup\$ Yes, that's right: I'm assuming here that the OP is starting from scratch. \$\endgroup\$Gareth Rees– Gareth Rees2013年11月13日 15:54:41 +00:00Commented Nov 13, 2013 at 15:54
Explore related questions
See similar questions with these tags.
lang-py
i
orI
, unless you need more than 32 bits. \$\endgroup\$