Reading binary files

Discussion in 'Python' started by amfr, Nov 23, 2005.

  1. amfr

    amfr Guest

    On windows, is there anything special I have to do to read a binary
    file correctly?
     
    amfr, Nov 23, 2005
    #1
    1. Advertisements

  2. Open it in binary mode?
     
    Grant Edwards, Nov 23, 2005
    #2
    1. Advertisements

  3. 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>
     
    Fredrik Lundh, Nov 23, 2005
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.