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

Chỉ định buffer size khi mở file trong Python (open buffering)

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 ý
0UnbufferedChỉ binary mode
1Line bufferedChỉ text mode
>1Block buffered (size bytes)Text/binary
-1 (default)Hệ thống quyết địnhThườ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.