Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การอ่านไฟล์ด้วย Buffer Size จำกัดใน Python (f.read(size))

เมธอด read(size) ของ File Object อ่านข้อมูล สูงสุด size ไบต์ จากตำแหน่ง Pointer ปัจจุบัน

ตัวอย่าง: อ่าน 10 ไบต์

>> with open('my_file.txt', 'r') as f:
...     print(f.read(10))  # อ่าน 10 ไบต์แรก
Hello worl

สมมติเนื้อหาไฟล์คือ Hello world! → อ่าน 10 ไบต์ ได้ Hello worl

การอ่านแบบทีละชิ้น (Chunked Reading)

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

อ่านทีละบรรทัด (Line by Line) - Memory Efficient

>> with open('large_file.txt', 'r') as f:
...     for line in f:  # File object เป็น Iterator ของบรรทัด
...         process(line)

Buffering ใน open()

พารามิเตอร์ buffering ใน open() ควบคุม Buffer ของ File Object เอง (ไม่ใช่ read(size)):

  • 0 - Unbuffered (Binary Mode เท่านั้น)
  • 1 - Line Buffered (Text Mode เท่านั้น)
  • >1 - Fixed-size Buffer (ประมาณ bytes)
  • -1 - System Default (Default)
>> # เปิดไฟล์ด้วย Buffer 128 bytes
>>> f = open('my_file', 'r', buffering=128)