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

Đọc file với buffer size giới hạn trong Python (read(size))

Phương thức file.read(size) đọc tối đa size bytes từ vị trí con trỏ hiện tại.

Ví dụ: Đọc 10 bytes

with open('my_file.txt', 'r') as f:
    print(f.read(10))  # đọc 10 ký tự đầu
# Output: Hello worl  (nếu file chứa "Hello world!")

Đọc vòng lặp theo chunk (streaming)

CHUNK_SIZE = 8192  # 8KB
with open('large_file.dat', 'rb') as f:
    while True:
        chunk = f.read(CHUNK_SIZE)
        if not chunk:
            break
        process(chunk)

Buffering khi open()

# Python 3
open('file', 'r', buffering=1)      # line buffered (text mode)
open('file', 'rb', buffering=8192)  # fixed buffer 8KB (binary)
open('file', 'rb', buffering=0)     # unbuffered (chỉ binary)

Mặc định: Text mode → line buffered (tty) hoặc block buffered; Binary → block buffered (~8KB).