all of the preceding examples process simple text filesbut python scripts can also open and process files containing binary data--jpeg imagesaudio clipspacked binary data produced by fortran and programsencoded textand anything else that can be stored in files as bytes the primary difference in terms of your code is the mode argument passed to the built-in open functionfile open('data txt''wb'file open('data txt''rb'open binary output file open binary input file once you've opened binary files in this wayyou may read and write their contents using the same methods just illustratedreadwriteand so on the readline and readlines methods as well as the file' line iterator still work here for text files opened in binary modebut they don' make sense for truly binary data that isn' line oriented (end-of-line bytes are meaninglessif they appear at allin all casesdata transferred between files and your programs is represented as python strings within scriptseven if it is binary data for binary mode filesthoughfile content is represented as byte strings continuing with our text file from preceding examplesopen('data txt'read('hello file world!\nbye file world \nthe life of briantext modestr open('data txt''rb'read(binary modebytes 'hello file world!\ \nbye file world \ \nthe life of brianfile open('data txt''rb'for line in fileprint(lineb'hello file world!\ \nb'bye file world \ \nb'the life of brianthis occurs because python treats text-mode files as unicodeand automatically decodes content on input and encodes it on output binary mode files instead give us access to file content as raw byte stringswith no translation of content--they reflect exactly what is stored on the file because str strings are always unicode text in xthe special bytes string is required to represent binary data as sequence of byte-size integers which may contain any -bit value because normal and byte strings have almost identical operation setsmany programs can largely take this on faithbut keep in mind that you really must open truly binary data in binary mode for inputbecause it will not generally be decodable as unicode text similarlyyou must also supply byte strings for binary mode output--normal strings are not raw binary databut are decoded unicode characters ( code pointswhich are encoded to binary on text-mode outputopen('data bin''wb'write( 'spam\ ' open('data bin''rb'read( file and directory tools