sys getdefaultencodingcontinuing our interactive sessionopen('data txt'' 'encoding='latin 'write(data open('data txt'' 'encoding='latin 'read('spamopen('data txt''rb'read( 'sp\xe mif we open in binary modethoughno encoding translation occurs--the last command in the preceding example shows us what' actually stored on the file to see how file content differs for other encodingslet' save the same string againopen('data txt'' 'encoding='utf 'write(data open('data txt'' 'encoding='utf 'read('spamopen('data txt''rb'read( 'sp\xc \xa mencode data per utf decodeundo encoding no data translations this timeraw file content is differentbut text mode' auto-decoding makes the string the same by the time it' read back by our script reallyencodings pertain only to strings while they are in filesonce they are loaded into memorystrings are simply sequences of unicode characters ("code points"this translation step is what we want for text filesbut not for binary because binary modes skip the translationyou'll want to use them for truly binary data if factyou usually must--trying to write unencodable data and attempting to read undecodable data is an erroropen('data txt'' 'encoding='ascii'write(dataunicodeencodeerror'asciicodec can' encode character '\xe in position ordinal not in range( open( ' :\python \python exe'' 'read(unicodedecodeerror'charmapcodec can' decode byte in position character maps to binary mode is also last resort for reading text filesif they cannot be decoded per the underlying platform' defaultand the encoding type is unknown--the following recreates the original strings if encoding type is knownbut fails if it is not known unless binary mode is used (such failure may occur either on inputting the data or printing itbut it fails nevertheless)open('data txt'' 'encoding='cp 'writelines(['spam\ ''ham\ ']open('data txt'' 'encoding='cp 'readlines(['spam\ ''ham\ 'open('data txt'' 'readlines(unicodedecodeerror'charmapcodec can' decode byte in position character maps to open('data txt''rb'readlines([ '\xa \ \ \ \ %\ \ \ \ %' file and directory tools