open('data bin''wb'write('spam\ 'typeerrormust be bytes or buffernot str but notice that this file' line ends with just \ninstead of the windows \ \ that showed up in the preceding example for the text file in binary mode strictly speakingbinary mode disables unicode encoding translationbut it also prevents the automatic endof-line character translation performed by text-mode files by default before we can understand this fullythoughwe need to study the two main ways in which text files differ from binary unicode encodings for text files as mentioned earliertext-mode file objects always translate data according to default or provided unicode encoding typewhen the data is transferred to and from external file their content is encoded on filesbut decoded in memory binary mode files don' perform any such translationwhich is what we want for truly binary data for instanceconsider the following stringwhich embeds unicode character whose binary value is outside the normal -bit range of the ascii encoding standarddata 'sp\xe mdata 'spam xe bin( xe )chr( xe ( ' '' 'it' possible to manually encode this string according to variety of unicode encoding types--its raw binary byte string form is different under some encodingsdata encode('latin ' 'sp\xe -bit charactersascii extras data encode('utf ' 'sp\xc \xa bytes for special characters only data encode('ascii'does not encode per ascii unicodeencodeerror'asciicodec can' encode character '\xe in position ordinal not in range( python displays printable characters in these strings normallybut nonprintable bytes show as \xnn hexadecimal escapes which become more prevalent under more sophisticated encoding schemes (cp in the following is an ebcdic encoding)data encode('utf ' '\xff\xfes\ \ \xe \ \ bytes per character plus preamble data encode('cp ' '\xa \ \ an ebcdic encodingvery different the encoded results here reflect the string' raw binary form when stored in files manual encoding is usually unnecessarythoughbecause text files handle encodings automatically on data transfers--reads decode and writes encodeaccording file tools