binary data

Skip Montanaro skip at
Thu Aug 26 17:52:15 CEST 1999

    Gerhard> How do I write binary data to a file?  I'm using open() and
    Gerhard> write and I always get the error that n is an integer.

I take it you're doing something like

    f = open("spam.bin", "w")
    n = 42

The file objects' write method only works with strings.  Take a look at the
struct module, which can pack the integer into a string:

    s = struct.pack("l", n)

If you don't really want the value written in binary, but in ascii, use the
% format operator instead:

    f.write("%d" % n)

Skip Montanaro |
skip at |
847-971-7098   | Python: Programming the way Guido indented...

More information about the Python-list mailing list