Reading binary files

Fredrik Lundh fredrik at pythonware.com
Wed Nov 23 17:19:36 EST 2005


"amfr" <amfr.org at gmail.com> wrote

> On windows, is there anything special I have to do to read a binary
> file correctly?

the documentation has the answer:

    http://docs.python.org/lib/built-in-funcs.html#l2h-25

    Append 'b' to the mode to open the file in binary mode, on
    systems that differentiate between binary and text files (else it
    is ignored). /.../

    When opening a binary file, you should append 'b' to the
    mode value for improved portability. (It's useful even on
    systems which don't treat binary and text files differently,
    where it serves as documentation.)

in other words, always use

    f = open(filename, "rb")

to open binary files for reading, on all platforms (but it only matters
on some platforms).  to open for writing, use

    f = open(filename, "wb") # create new file

or

    f = open(filename, "r+b") # open existing file for read/write

</F> 






More information about the Python-list mailing list