Print a string in binary format

Mark McEahern marklists at mceahern.com
Thu Jan 20 20:07:24 EST 2005


neutrino wrote:

>Greetings to the Python gurus,
>
>I have a binary file and wish to see the "raw" content of it. So I open
>it in binary mode, and read one byte at a time to a variable, which
>will be of the string type. Now the problem is how to print the binary
>format of that charater to the standard output. It seems a common task
>but I just cannot find the appropriate method from the documentation.
>Thanks a lot.
>

How is this *not* what you want:

    import sys
    f = open(filename, 'rb')
    data = f.read(1)
    while data:
        sys.stdout.write(data)
        data = f.read(1)

Of course, that's the long version of:

    print open(filename, 'rb').read()

// m



More information about the Python-list mailing list