# Writing integer to binary file

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):
data = str('{0:0x}'.format(Integer))
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
HexData = "".join(['{0:0x}'.format(ord(b)) for b in RawData])
return int(HexData, 16)

IntWrite("int_data.txt", 100000)

• This is more of a SO question. See struct.pack, struct.unpack, in this case with a format character of i or I, unless you need more than 32 bits. – Michael Urman Nov 13 '13 at 3:02
• … but it's also acceptable as a Code Review question. – 200_success Nov 13 '13 at 5:58
• Sure, especially if there is a need to handle arbitrarily large integers, which the original code seems to offer. Otherwise the best code is that which you don't have to write. :) – Michael Urman Nov 13 '13 at 13:16

Python comes with a built-in pickle module for serialization:
>>> import pickle

(P.S. I wouldn't use a filename ending with .txt to store binary data.)