Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chế độ 'b' (Binary) khi mở file trong Python

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ểmText mode ('r', 'w')Binary mode ('rb', 'wb')
Trả vềstr (Unicode)bytes
NewlineAuto convert (universal)Giữ nguyên
EncodingCần encoding (mặc định utf-8)Không có encoding
Dùng choFile 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