Do you want to write the string representation of an integer to a text file, as your code suggests ("123.
txt" and "w" mode instead of "wb"), or do you want to write the binary representation of an integer to a binary file? My question is meaningless if you're on a non-Microsoft system, but I had to ask, because the .txt extension is confusing.
In the first case, it's easy (there might be an even easier way, but I'm no Python expert), as you've found out yourself:
out = open("123.txt", "w")out.write(str(24))out.close()
In the second case, you'll have to use the
struct module, IIRC:
import structout = open("123.bin", "wb") # note: 'b' for binary mode, important on Windowsformat = "i" # one integerdata = struct.pack(format, 24) # pack integer in a binary stringout.write(data)out.close()
Reading back from the file:
import structinput = open("123.bin", "rb")data = input.read()input.close()format = "i"value, = struct.unpack(format, data) # note the ',' in 'value,': unpack apparently returns a n-uple