December 2018
Beginner to intermediate
796 pages
19h 54m
English
Notice that by opening a file passing t in the options (or omitting it, as it is the default), we're opening the file in text mode. This means that the content of the file is treated and interpreted as text. If you wish to write bytes to a file, you can open it in binary mode. This is a common requirement when you deal with files that don't just contain raw text, such as images, audio/video, and, in general, any other proprietary format.
In order to handle files in binary mode, simply specify the b flag when opening them, as in the following example:
# files/read_write_bin.pywith open('example.bin', 'wb') as fw: fw.write(b'This is binary data...')with open('example.bin', 'rb') as f: print(f.read()) # prints: ...Read now
Unlock full access