--againa desired result for binary data type requirements and file behavior are the same even if the data we're writing to the binary file is truly binary in nature in the followingfor examplethe "\ is binary zero byte and not printable characterwrite and read truly binary data open('temp''wb'write( ' \ ' open('temp'' 'read(' \ copen('temp''rb'read( ' \ cprovide bytes receive str receive bytes binary-mode files always return contents as bytes objectbut accept either bytes or bytearray object for writingthis naturally followsgiven that bytearray is basically just mutable variant of bytes in factmost apis in python that accept bytes also allow bytearraybytearrays work too ba bytearray( '\ \ \ 'open('temp''wb'write(ba open('temp'' 'read('\ \ \ open('temp''rb'read( '\ \ \ type and content mismatches in notice that you cannot get away with violating python' str/bytes type distinction when it comes to files as the following examples illustratewe get errors (shortened hereif we try to write bytes to text file or str to binary file (the exact text of the error messages here is prone to change)types are not flexible for file content open('temp'' 'write('abc\ ' open('temp'' 'write( 'abc\ 'typeerrormust be strnot bytes text mode makes and requires str open('temp''wb'write( 'abc\ 'binary mode makes and requires bytes open('temp''wb'write('abc\ 'typeerror'strdoes not support the buffer interface this makes sensetext has no meaning in binary termsbefore it is encoded although it is often possible to convert between the types by encoding str and decoding bytesas described earlier in this you will usually want to stick to either str for text data or bytes for binary data because the str and bytes operation sets largely intersectthe choice won' be much of dilemma for most programs (see the string tools coverage in the final section of this for some prime examples of this unicode and byte strings