Reading and writing in binary mode

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.py
with open('example.bin', 'wb') as fw:
fw.write(b'This is binary data...')

with open('example.bin', 'rb') as f:
print(f.read()) # prints: b'This is binary data...'

In this example, I'm still using text as binary data, but it could be anything you want. You can see it's treated as a binary by the fact that you get the b'This ...' prefix in the output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.125.100