Hàm open() chấp nhận tham số buffering (thứ 3 Python 2, keyword-only Python 3).
Giá trị buffering
| Giá trị | Chế độ | Lưu ý |
|---|---|---|
0 | Unbuffered | Chỉ binary mode |
1 | Line buffered | Chỉ text mode |
>1 | Block buffered (size bytes) | Text/binary |
-1 (default) | Hệ thống quyết định | Thường line buffered (tty) hoặc block buffered |
Ví dụ
# Mở file text với buffer 128 bytes
f = open('my_file', 'r', buffering=128)
# Binary unbuffered
f = open('my_file', 'rb', buffering=0)
# Line buffered (text)
f = open('my_file', 'r', buffering=1)
Mặc định Python 3
- Binary: fixed-size chunk (~8KB, heuristic block size).
- Text tty (terminal): line buffered.
- Text file thường: block buffered.