Thêm 'b' vào mode để mở file ở binary mode (nhị phân). Mặc định là text mode ('t').
Ví dụ
# Binary read
with open('image.png', 'rb') as f:
data = f.read() # bytes object
# Binary write
with open('output.bin', 'wb') as f:
f.write(b'\x00\x01\x02')
Khác biệt Text vs Binary
| Đặc điểm | Text mode ('r', 'w') | Binary mode ('rb', 'wb') |
|---|---|---|
| Trả về | str (Unicode) | bytes |
| Newline | Auto convert (universal) | Giữ nguyên |
| Encoding | Cần encoding (mặc định utf-8) | Không có encoding |
| Dùng cho | File text: .txt, .csv, .json... | File nhị phân: ảnh, audio, video, exe... |
Kết hợp mode
open('file', 'r+b') # read/write binary
open('file', 'w+b') # write/read binary (truncate)
open('file', 'a+b') # append binary